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.
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.