套接字多客户端一台服务器

时间:2017-01-23 16:08:19

标签: c# sockets server client tcpclient

如何停止向客户端发送消息,而客户端不会从服务器读取消息。为了更好地理解这意味着什么,请考虑客户端长时间不调用Read的情况,并且服务器停止向此客户端发送消息。 Server.cs从客户端接收消息,并发送给所有客户端

private static void ReceiveCallback(IAsyncResult AR)
        {
            Socket current = (Socket)AR.AsyncState;
            int received;
            try
            {
                received = current.EndReceive(AR);
            }
            catch (SocketException)
            {
                Console.WriteLine("Client forcefully disconnected");
                current.Close();
                clientSockets.Remove(current);
                return;
            }
            byte[] recBuf = new byte[received];
            Array.Copy(buffer, recBuf, received);
            string text = Encoding.ASCII.GetString(recBuf);
            Console.WriteLine("Received Text: " + text);
            buffQueue.Enqueue(text);
            current.BeginReceive(buffer, 0, BUFFER_SIZE, SocketFlags.None, ReceiveCallback, current);
            foreach (var client in clientSockets)
            {
                foreach (var msg in buffQueue)
                {
                    Sendata(client, text);
                }
                }
            }
       static void Sendata(Socket socket, string noidung)
        {
            byte[] data = Encoding.ASCII.GetBytes(noidung);
            socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallback), socket);

        }
        private static void SendCallback(IAsyncResult AR)
        {
            Socket socket = (Socket)AR.AsyncState;
            socket.EndSend(AR);

        }

Client.cs

public void ReceiveMessage(IAsyncResult ar)
        {
            Random rnd = new Random();
            Socket socket = (Socket)ar.AsyncState;
            int received = socket.EndReceive(ar);
            byte[] dataBuf = new byte[received];
            Array.Copy(receivedBuf, dataBuf, received);
            string msg = Encoding.ASCII.GetString(dataBuf);
            Console.WriteLine("> " + msg + '\n');
            ClientSocket.BeginReceive(receivedBuf, 0, receivedBuf.Length, SocketFlags.None,
                new AsyncCallback(ReceiveMessage), ClientSocket);
        }

1 个答案:

答案 0 :(得分:0)

问题是,当客户端没有读取缓冲区时,客户端的receivebuffer将被填满,服务器将阻塞执行。您可以通过以下方式阻止这种情况:

  • 为每个客户端排队数据。客户端必须请求数据,因此服务器将发送它的队列。 (在另一个主题上)
  • 使用服务器上套接字上的socket.Blocking = false。当服务器发送数据并且缓冲区已满时,您将获得一个WouldBlock异常,或者在发送时使用正确的重载时,将返回SocketErrorCode。 Windows Sockets: Blocking。你还需要一个队列。

SendData可以并行完成,因为bytebuffer / data在发送时不会发生变化。