Hi,
I've just started looking at HTTP etc. and have written a simple Java Client that uses URLConnection to send a URL to a server and pulls down the index.html page (as plain text).
Now I'm working on a simple server but I'm stuck at the first hurdle, (well maybe 2nd or 3rd), I can't get it to respond to the client properly.
Here is the reading in loop and it reads in the HTTP request fine, even from FF and IE etc:
while((message = in.readLine()) != null)
{
System.out.println(message);
out.write("something");
}
The problem is that I don't know how to get it to respond anything useful. If I let it do what it is doing in the above code it sends "something" 6 times to my client (as there are 6 lines to the HTTP request) but nothing to FF/IE etc.
Also, it doesn't seem to break the loop ever as I added a System.out.println("test");
line to print after the loop but the server never seems to reach that point, should it? Should readLine() return null at the end of the first HTTP request?
I've been reading stuff on the sun and oracle websites but am still pretty stuck as to how this should work.
Thanks for your time,
Infinitifizz
EDIT: Oops, forgot to copy the code in.
Server.java:
package exercise2;
import java.net.*;
public class Server
{
public static void main(String[] args) throws Exception
{
boolean listening = true;
ServerSocket server = new ServerSocket(8081);
while(listening)
{
Socket client = server.accept();
new ServerThread(client).start();
}
server.close();
}
}
ServerThread.java:
package exercise2;
import java.io.*;
import java.net.*;
public class ServerThread extends Thread
{
private Socket socket = null;
public ServerThread(Socket s)
{
this.socket = s;
}
public void run()
{
try
{
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
String message, reply = "";
while((message = in.readLine()) != null)
{
System.out.println(message);
out.write("something");
}
System.out.println("test");
in.close();
out.close();
socket.close();
}
catch(IOException e)
{
System.err.println("error");
}
}
}