I am trying to make a web chat to integrate with other languages.
I am willing to create my own webserver in java.. that knows only to respond to a specific request.
I have a socket that is listening to port 80. answering with
out.print("HTTP/1.1 200 OK\r\n");
out.print("Content-Type: text/plain\r\n\r\n");
out.println("We have a text now");
out.print("\r\n");
out.print("\r\n");
out.print("0");
out.print("\r\n");
out.print("\r\n");
My problem is… is there any way to use partial response to keep the browser’s socket open?
I want to send the messages only when they exist.. in this case messages will be sent almost instantly..
P.S: I am not talking about web-sockets because not all programs support web-sockets… only browsers do… (programs that don’t support web-sockets: Internet Explorer)
My question is if I can use partial response (206) in this case.. and how to keep the page “loading” and also send partial text… ??… Do I have to say content-length or something? what header do I have to write… I know only for several statuses (200, 301, 404, etc). For 206 I don’t know what to write on first, second, third line.. how to send the response (as xml, text, or can I define content type?) and how to read it from javascript?
For example I want this code to write every second something:
out.print("HTTP/1.1 200 OK\r\n");
out.print("Content-Type: text/plain\r\n\r\n");
for (int i = 0; i < 10; i++)
{
out.println("We have a text now");
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
out.print("\r\n");
out.print("\r\n");
out.print("0");
out.print("\r\n");
out.print("\r\n");
Regards
Any decent http client will use http keep-alives, so if a user makes a request again within a few seconds they will not need to open a new connection. If you write your own web-server you will have to make sure to implement this or the implementation will be slower than a standard web server or web container (e.g. tomcat or jetty). Also, since many languages have good http libraries, you don’t need a custom implementation of a web server for this either.
If you’ve written a servlet, it is possible to simply never return from the http response and then just write responses out as they come. This will tie up threads on the server though and probably won’t scale very well.
You could try one of the asynchronous http implementations (e.g. netty or mina) and have a go at it, but that is significantly more work — although it would still be far less work than trying to roll your own.