简体   繁体   English

C#通过UDP接收

[英]C# Receive over UDP

I am writing a program that has to send data over UDP to a specific server (which works) and also receive data from that server (which doesn't work). 我正在编写一个程序,该程序必须通过UDP将数据发送到特定的服务器(有效),并且还必须从该服务器接收数据(无效)。 The problem is, that the port i am sending data to is not the same that dat from the server come from. 问题是,我要向其发送数据的端口与来自服务器的dat来自的端口不同。

Server: Listens on one port, creates new sockets (on different ports) for each client to send data. 服务器:侦听一个端口,为每个客户端创建新的套接字(在不同的端口上)以发送数据。

I have the following code (client side): 我有以下代码(客户端):

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);

This successfully connects to my server application and sends the data it's supposed to. 这成功连接到我的服务器应用程序并发送了应该发送的数据。 However, MessageCallBack never gets called: 但是,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);
}

I think the problem is that the client socket is still connected to the port on the server, and only accepts data from that port, but to my knowledge this isn't a problem when using BeginReceive instead of BeginReceiveFrom. 我认为问题在于客户端套接字仍连接到服务器上的端口,并且仅接受来自该端口的数据,但是据我所知,使用BeginReceive而不是BeginReceiveFrom时这不是问题。

When using UDP you can't use the Send and BeginReceive methods, because those are connection-oriented (TCP). 使用UDP时,不能使用Send和BeginReceive方法,因为它们是面向连接的(TCP)。 Instead use the Socket.SendTo and Socket.BeginReceiveFrom. 而是使用Socket.SendToSocket.BeginReceiveFrom。 It should work using those methods. 它应该使用这些方法工作。

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

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