且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

多线程应用程序中的问题.

更新时间:2022-04-08 22:51:16

您需要对代码进行一些拆分,我的建议是:

ServerApp
创建并启动用于管理所有连接的Server.

服务器
在它自己的线程上运行,并包含一个接受入站连接的Listener和所有连接的Session集合.

Listener
在它自己的线程中运行,创建一个ServerSocket,并为分配给Server的每个Socket创建一个Session.

会话
再次在它自己的线程上运行.
从客户端获取入站消息,并将其转发到Server.
接受来自Server的出站消息并将其转发给客户端.

三个服务器端组件中的每个组件都必须是线程安全的,并且可以在两个位置调用同步方法.
我将通过在所有会话的Server中具有集合来管理一切,然后Session本身将保留消息以进行处理,并在有消息时通知服务器.

如果您想要更多的想法,请尝试搜索多线程聊天服务器",因为那样可能会为您提供很多您需要涵盖的概念,而又不会太复杂.
You need to split up your code a bit, my suggestion would be:

ServerApp
Creates and starts a Server that manages all the connections.

Server
Runs on it''s own thread and contains a single Listener that accepts inbound connections and a collection of Sessions for all of the connections.

Listener
Runs in it''s own thread, creates a ServerSocket and creates a Session for each Socket that is given to the Server.

Session
Again runs on it''s own thread.
Takes inbound messages from the client and forwards them to the Server.
Accepts outbound messages from the Server and forwards them to the client.

Each of the three server side components need to be thread safe, synchronize methods that can be called from two places.
I would manage everything by having a collection in the Server of all the sessions and then the Sessions themselves will keep the messages for processing and notify the server when they have something.

If you want more ideas, try searching for "multi threaded chat server" as that would probably give you a lot of the concepts you need to cover without being too complicated.