繁体   English   中英

C#UdpClient服务器和客户端问题

[英]C# UdpClient server and client issue

这是我的服务器代码

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.

有人能帮我吗?

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

检出JoinMulticastGroup就像 Connect for TcpClient)。 您需要在广播之前(即,如果要广播)执行此操作。

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

暂无
暂无

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

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