简体   繁体   English

套接字发送客户端列表

[英]Socket send a list of clients

I'm not very skilled in C#, but I'm using it for an homework. 我不太熟练C#,但是我正在用它来做作业。 I created a function to send a list of clients connected to a server to the other clients 我创建了一个函数,用于将连接到服务器的客户端列表发送给其他客户端

private void SendListToClients()
    {
        Socket userSocket=null;
        string username = null;
        string role = null;
        foreach (User Users in UserList)
        {
            userSocket = Users.getSocket();
            username = Users.getUsername();
            role = Users.getRole();
            userSocket.Send(Encoding.ASCII.GetBytes("!ListStart\n"));
            for(int i=0;i<UserList.Count;i++)
            {
                User UsersControl = (User)UserList[i];
                string roleU = UsersControl.getRole();
                string usernameU = UsersControl.getUsername();

                userSocket.Send(Encoding.ASCII.GetBytes("!ClientList:"+usernameU + ":" + roleU+"\n"));       
            }

        }
    }

My problem is in the line userSocket.Send(), when I receive this at the client side I don't receive (if the user in the list are 5 for example) 5 send, but 1 send with all the 5 users. 我的问题是在userSocket.Send()行中,当我在客户端收到此消息时,我没有收到(例如,如果列表中的用户是5个)5个发送,而所有5个用户却发送了1个。 How can I solve this? 我该如何解决? Otherwise there's the possibility to send my Object (UserList) enterly over the socket? 否则,可以通过套接字输入我的对象(UserList)吗?

From the Socket.Receive Method documentation: Socket.Receive方法文档中:

If you are using a connection-oriented Socket, the Receive method will read as much data as is available, up to the size of the buffer. 如果您使用的是面向连接的Socket,则Receive方法将读取尽可能多的数据,直到缓冲区的大小。

Hence, even though the server sent five messages one at a time, all of them were stored in the client's input buffer and read at once. 因此,即使服务器一次发送了五条消息,它们也都存储在客户端的输入缓冲区中并立即读取。

What you are seeing is by design. 您所看到的是设计使然。 This is how TCP works. 这就是TCP的工作方式。 Or as others will tell you, "TCP is a stream protocol, not a message protocol." 或者就像其他人会告诉您的那样,“ TCP是流协议,而不是消息协议。”

Short summary: Just because you "sent" N bytes, doesn't mean you will "receive" N bytes. 简短摘要:仅因为您“发送”了N个字节,并不意味着您将“接收”了N个字节。 TCP will stream the bytes independent of how the app structured its "send" calls. TCP将流传输字节,而与应用程序如何构造其“发送”调用无关。 Your receive side code should be prepared to handle receiving byte chunks of all different sizes and not necessarily in blocks equal to your applications message size 您的接收方代码应准备好处理所有不同大小的接收字节块,而不必以等于您的应用程序消息大小的块为单位

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

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