【问题标题】:C# UdpClient server and client issueC# UdpClient 服务器和客户端问题
【发布时间】:2023-05-30 19:33:01
【问题描述】:

这是我的服务器代码

byte[] data = new byte[1024];
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);
UdpClient newsock = new UdpClient(ipep);

Console.WriteLine("Waiting for a client...");

IPEndPoint send = new IPEndPoint(IPAddress.Any, 0);

byte[] data1 = newsock.Receive(ref send);
int test1 = BitConverter.ToInt32(data1, 0);
Console.WriteLine("test1 = {0}", test1);

这是我的客户端代码

byte[] data = new byte[1024];
string stringData;
UdpClient server = new UdpClient("127.0.0.1", 9050);

IPEndPoint send = new IPEndPoint(IPAddress.Any, 0);

int test1 = 45;

byte[] data1 = BitConverter.GetBytes(test1);
server.Send(data1, data1.Length);

根据我的客户端和服务器, 客户端是向服务器发送数据的那个。

但我的要求是相反的!我无法做到这一点.. 当我尝试将此代码添加到服务器时

byte[] buffer = ASCIIEncoding.ASCII.GetBytes("Hello Client");
newsock.Send(buffer, buffer.Length);

我得到一个异常为The operation is not allowed on non-connected sockets.

有人可以帮我吗?

【问题讨论】:

    标签: c# sockets networking udp udpclient


    【解决方案1】:

    UDP 是无连接的。当您在 UDP 套接字上调用 connect 时,您实际上只是在设置默认目标 IP 和端口。另一端的接收者必须使用Socket.ReceiveFrom(在UNIX 中称为recvfrom)来找出数据包的来源,然后SendTo 来回复原始请求。服务器可以使用connect,但如果你想支持多个客户端,那会很尴尬。

    【讨论】:

      【解决方案2】:

      查看JoinMulticastGroup类似 Connect for TcpClient)。您需要在广播之前执行此操作(也就是说,如果您正在广播)。

      UdpClient 的文档也会对您有所帮助。

      【讨论】:

      • 组播是一个独立的概念。典型的客户端-服务器 UDP 应用程序不会使用多播。
      • @Ben:很公平,我猜 UdpClient 的文档就是真正需要的所有 OP。