19 May 2010

How to know the Socket has end of HTTP stream

To know when the HTTP request finishes, you have to check for "\n\r" characters.

See the following java code:


public class Server{
public static void main(String[] args) throws Exception{
ServerSocket ssocket = new ServerSocket(6666);
Socket socket = ssocket.accept();

InputStream is = socket.getInputStream();
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);

ByteArrayOutputStream baos = new ByteArrayOutputStream();

byte[] buff = new byte[1024];

int len = 0;
while ((len = is.read(buff)) != -1) {
baos.write(buff, 0, len);
if (endOfRequest(buff)) break;
}
baos.close();

writer.println("<html>Hello World</html>");

is.close();
writer.close();
socket.close();
System.out.println(baos.toString());
}

private static boolean endOfRequest(byte[] buff) {
for (int i=1; i<buff.length;i++) {
if ( buff[i-1] == 10 && buff[i] == 13)
return true;
}
return false;
}
}
Post a Comment