Reputation: 3805
I'm coding a server and this is how it looks now:
import java.net.ServerSocket;
import java.net.Socket;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class HttpServer {
public static void main(String[] args) throws Throwable {
//http://localhost:3000
ServerSocket ss = new ServerSocket(3000);
while (true) {
//Waiting for socket
Socket s = ss.accept();
System.out.println("Client accepted");
//The main process
new SocketProcessor(s,ss).start();
}
}
private static class SocketProcessor implements Runnable {
private Thread t;
private Socket s;
private ServerSocket ss;
private InputStream is;
private OutputStream os;
private SocketProcessor(Socket s,ServerSocket ss) throws Throwable {
t = new Thread(this, "Server Thread");
this.ss=ss;
this.s = s;
this.is = s.getInputStream();
this.os = s.getOutputStream();
}
public void run() {
try {
readInputHeaders();
Thread.sleep(10000);
writeResponse("<html><body><h1>Hello</h1></body></html>");
} catch (Throwable t) {
/*do nothing*/
} finally {
try {
s.close();
} catch (Throwable t) {
}
}
System.out.println("Client processing finished");
}
public void start()
{
t.start();
}
private void writeResponse(String s) throws Throwable {
String response = "HTTP/1.1 200 OK\r\n" +
"Server: Server\r\n" +
"Content-Type: text/html\r\n" +
"Content-Length: " + s.length() + "\r\n" +
"Connection: close\r\n\r\n";
String result = response + s;
os.write(result.getBytes());
os.flush();
}
private void readInputHeaders() throws Throwable {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while(true) {
String s = br.readLine();
System.out.println(s);
if(s == null || s.trim().length() == 0) {
break;
}
}
}
}
}
Doesn't this
while (true) {
//Waiting for socket
Socket s = ss.accept();
System.out.println("Client accepted");
//The main process
new SocketProcessor(s,ss).start();
}
make webserver multithreaded? I was trying to run http://localhost:3000
from 2 different tabs in my browser. As you can see, I make my server wait for 10 seconds before response, so every page should take equal time. But no, it's not: first opened page takes 10, and 2nd - 20.
What's wrong?
UPD: I have thoughts, that ss.accept();
freezes server.
Upvotes: 1
Views: 174
Reputation: 643
Oh I see what is going on, are you opening two tabs in a single browser and connecting to your program? So it might be your browser that is serializing your requests.
If you open two browsers and make a request, your program will work as intended.
Upvotes: 1
Reputation: 462
Tried on different browsers and this doesn't happen in them. You are using chrome as I was? It may be chrome doing some strange stuff for same requests.
Note that I do
http://localhost:3000
and
http://localhost:3000?diff=true
and I get both of them in 10 seconds instead of 10 and 20 for the same request.
I would still love from someone to explain this, but maybe thats another question.
Upvotes: 2