Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multithread server program in Java

I am trying to write a multithread program in Java where a server listens for connections from clients and spawns a thread to acommodate each client. I have:

while(true)
    {
        Socket s = server.accept();    
        ClientHandler ch = new ClientHandler(s);
        Thread t = new Thread(ch);
        t.start();  
    }

My question is: whenever it accepts a connection in

Socket s = server.accept();

and starts executing the following lines of code to create the thread etc., what happens to a request for connection from a client during that time. Is it queued somehow and it will get served in the next loop of while(true) or will it be rejected?

thanks, Nikos

like image 673
nikos Avatar asked Dec 01 '11 18:12

nikos


2 Answers

After the accept() returns the TCP handshake is complete and you have a connected client socket (s in your code). Until the next call to accept() the OS queues pending connection requests.

You might want to check out some tutorial like this one for example.

like image 81
Nikolai Fetissov Avatar answered Sep 25 '22 00:09

Nikolai Fetissov


I wrote a tiny http server in Java, which you can find on github. That might be a good example for you to take a look at real-world usage of Sockets and multithreading.

like image 29
Xiaowei Chen Avatar answered Sep 26 '22 00:09

Xiaowei Chen