更新时间: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 aServer
that manages all the connections.
Server
Runs on it''s own thread and contains a singleListener
that accepts inbound connections and a collection ofSession
s for all of the connections.
Listener
Runs in it''s own thread, creates aServerSocket
and creates aSession
for eachSocket
that is given to theServer
.
Session
Again runs on it''s own thread.
Takes inbound messages from the client and forwards them to theServer
.
Accepts outbound messages from theServer
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 theServer
of all the sessions and then theSession
s 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.