简体   繁体   中英

Java Chat Multi-Client Receiving thread

In a lot of multclient java programs people use a separate thread which only receives the messages from the server. Is it really necessary? Why can't it be done in the main thread? What should be the problem?

For me a separate thread to receive the messages from the server is not that necessary, it could be done simply be the main.

Am I wrong?

No, if it was done in the main method, then the rest of your application would wait until a message is received. This may be fine if your application only received messages. However, if your application did other things like accepting user input in order to send messages then, the application would not be able to do the other tasks(such as user Input) until a message has been received.

EDIT:

It would also have a hard time with multiple clients

Yes you are. At least if you want something pratical. If you get updates periodical, you need to wait every x ms/s/mins for the server input to be read, if you receive message from the server directly you need to wait everytime someone sends one, and could not even handle multiple messages at once.

Now add a Graphical Interface and youll run into a wall trying to handle that by 1 thread.

Not that it would make sense anyway.

After 6 years I would like to answer myself of the past.

Some more context: the multi-client chat is a GUI chat that used swing. It was a high school project.

The main method would go in a loop to read messages received from a server. Since every other client action is event-based, the event handling would be done on a separate thread anyway.

So yeah, it worked fabulously at the time!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM