简体   繁体   English

Java Chat多客户端接收线程

[英]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.在许多多客户端 java 程序中,人们使用一个单独的线程,它只接收来自服务器的消息。 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.不,如果它是在 main 方法中完成的,那么应用程序的其余部分将等待直到收到消息。 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.如果您定期获得更新,则需要每 x ms/s/mins 等待一次读取服务器输入,如果您直接从服务器接收消息,则每次有人发送消息时都需要等待,甚至无法处理多条消息一次。

Now add a Graphical Interface and youll run into a wall trying to handle that by 1 thread.现在添加一个图形界面,你会遇到一堵墙,试图通过 1 个线程来处理它。

Not that it would make sense anyway.并不是说无论如何它都有意义。

After 6 years I would like to answer myself of the past. 6 年后,我想回答过去的自己。

Some more context: the multi-client chat is a GUI chat that used swing.更多上下文:多客户端聊天是使用swing 的GUI 聊天。 It was a high school project.这是一个高中项目。

The main method would go in a loop to read messages received from a server. main 方法将循环读取从服务器接收到的消息。 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!所以是的,它在当时非常有效!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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