Question

I am writing a client-server application in Java. The procedure is as following:

  1. A client send a message of HTTP format to a registration node with

    • a request line a number of header lines
    • a blank line
    • and a body.
    • (ASCII text)
  2. The registration node send a message of similar format to a server.

  3. The client and server can talk (pretty like SIP).

For now, I already have created sockets of client and server, but if I want to use DataInputStream and DataOutputStream to input and output data, I also need to determine the type of data since methods like readDouble from DataInputStream.

I don't know how to do it.

Sorry if my description is a little ambiguous, Here, some sample messages that would be transferred.

REGISTER john@google.com SIPL/1.0CRLF
To: john@google.comCRLF
From: john@google.comCRLF
Call-ID: a74fbCRLF
CSeq: 0CRLF
Expires: 200CRLF
Contact: 74.125.226.161:20132CRLF
CRLF

SIPL/1.0 200 okCRLF
To: barney@google.comCRLF
From: 74.125.226.161:20300CRLF
Call-ID: 9934bcd2CRLF
CSeq: 10CRLF
Content-Length: 21CRLF
Contact: 74.125.226.161:20305CRLF
CRLF
file=foo
characters=10

Any apply will really be appreciated !!!

Was it helpful?

Solution

Since you are reading ASCII text, and have to deal with line breaks, you can use readers and writers, and read your data with a java.io.BufferedReader which allows you to read line by line.

BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

String line = reader.readLine();
StringBuilder buffer = new StringBuilder();
while ( line != null) {
   buffer.append(line);
   line = reader.readLine();

   // you can check here if the line is empty and decide only to read the header
   // or to split your header and body into different buffers

}
String fullText = buffer.toString();

If you send text data, you can also use something similar:

PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
writer.println("GET / HTTP/1.1");
writer.println("Header: value");
writer.println(); // end of header
...
writer.flush(); // if you need to flush the buffer before closing
writer.close(); // when done - flushes and closes

Place everything in a try-catch-finally block with the close() methods in the finally (or, if you use Java 7, a try-with-resources)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top