0

I am writing a Client, Server-based chat. The Server is the central component and handles all the incoming messages and outgoing messages. The clients are that chat users. They see the chat in a frame and can also write chat messages. These messages are sent over to the server. The server in turn updates all clients.

My problem is synchronisation of the clients. Since the server is multi-threaded, both messages can be received from clients and updates (in form of messages) have to be sent out aswell. Since each client is getting updated in in its own thread, there is no guarantee that all clients will receive the same messages. We have a snychronisation problem.

How do I solve it?

I have messed with timestamps and a buffer. But this is not a good solution again because there is no guarantee that after assigning a timestamp the message will be put into the buffer immediately afterwards.

I shall add that I do not know the clients. That is, I only have one open connection in each thread on the server. I do not have an array of clients or something like that to keep track of all the clients.

4

1 回答 1

0

我建议您为每个客户端代理(即管理与每个客户端的通信的对象)实现一个队列。服务器对象(在自己的线程上)的每次迭代工作: 1. 它首先从所有客户端代理的队列中读取消息 2. 根据其内部逻辑和传入消息决定是否需要发送任何消息 3. 准备和将任何传出消息放入其所有客户端代理的队列中。

客户端代理线程的工作时间表是这样的: 1. 从通信中读取。2. 从客户端代理写入队列到服务器(如果收到任何消息)。3. 从服务器到客户端代理的队列中读取。4. 将通信通道写入客户端(如果需要)。

您可能必须在每个队列上都有一个互斥锁。希望有帮助

于 2013-10-20T07:05:55.843 回答