问题
I am currently learning how to program a tcp server in java. I am creating a new thread for new each client connection (multithreaded server).
After the client connects to the server, I want to send data from the client to the server. On serverside the server is in a while loop reading data from the sockets inputstream. I want to ask now: Should I create a new thread for each received packet?
For example the client sends the string "Hello". Should the server handle this packet in a new thread so it can continue reading, because I think if I don't create a new thread, server doesn't go back on reading and if client sends another packet after the "Hello" packet for example "Bye", the server might not read it because it could still be busy handling the "Hello" packet.
To be clear I am not talking about serversockets accept method, I am talking about the data from sockets inputstream.
Please enlighten me about this.
回答1:
If your packet handle task is not very heavy (probably it is not), you shouldn't. Thread will handle a message and come back to receiving new messages. No data will be lost - if nobody reads from inputstream, data transfer just holds (after all buffers filled). Just keep one thread per client, it is enough in most cases.
回答2:
Yes you must delegate to another thread in order to have a responsive server. No, don't create a thread per request (unless the client load is trivial) but use a thread pool instead. Example skeleton code (of course you will have to break out of the loop somehow):
private static final ExecutorService threadPool = Executors.newCachedThreadPool();
while(true){
final Socket clientConnection = serverSocket.accept();
threadPool.execute(new Runnable(){
public void run(){
processConnection(clientConnection);
});
}
Should I create a new thread for each received packet?
No. Each thread will process its own connection (which receives the client packets) so connecting clients will be serviced faster since the main listener will continue accepting connections
回答3:
One thread per each client connection is fine for a small application. However, one thread per each client request / packet is not a good approach at all. Just make sure your server can communicate to the client in time.
Please note that the number of threads you create is no way unlimited, it depends on the OS you are working with. Real applications use thread pools for handling such cases.
来源:https://stackoverflow.com/questions/12017575/java-server-start-a-new-thread-for-each-received-packet