【发布时间】:2016-05-27 19:42:58
【问题描述】:
我正在编写一个程序,该程序必须通过 UDP 将数据发送到特定服务器(可以工作)并从该服务器接收数据(不工作)。 问题是,我发送数据的端口与来自服务器的数据来自的端口不同。
服务器:侦听一个端口,为每个客户端创建新的套接字(在不同的端口上)以发送数据。
我有以下代码(客户端):
socker = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint epLocal = new IPEndPoint(myIp, localPort);
socket.Bind(epLocal);
IPAddress ipAddressremote = IPAddress.Parse(remoteIp);
remoteEP = new IPEndPoint(ipAddressremote, port);
socket.Connect(remoteEP);
byte[] buffer = new byte[1024];
socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(MessageCallBack), buffer);
socket.Send(someByteArray);
这成功连接到我的服务器应用程序并发送它应该发送的数据。但是,MessageCallBack 永远不会被调用:
private void MessageCallBack(IAsyncResult iAsyncResult)
{
byte[] receivedData = (byte[])iAsyncResult.AsyncState;
ASCIIEncoding eEncoding = new ASCIIEncoding();
string receievedMessage = eEncoding.GetString(receivedData);
handleMessage(receievedMessage);
byte[] buffer = new byte[1024];
socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(MessageCallBack), buffer);
}
我认为问题在于客户端套接字仍然连接到服务器上的端口,并且只接受来自该端口的数据,但据我所知,使用 BeginReceive 而不是 BeginReceiveFrom 时这不是问题。
【问题讨论】:
-
为什么 UDP 服务器需要为每个客户端创建一个新的套接字?
-
如果服务器需要向多个客户端发送数据,我认为这就是我要走的路……我错了吗?
-
确实没有理由这样做。单插座就可以了。
-
让它与单个套接字一起工作,谢谢!甚至不知道为什么我首先以其他方式这样做:D
-
我建议你看看UdpClient,它可能会让你的生活更轻松。