问题
I'm new to UDP. Using a test environment, I am able to send/receive a single UDP message. However, I’m trying to figure out how to receive multiple UDP messages. I'd like MyListener service to receive UDP packets all day long, whenever I send them. I appreciate any help.
PS - As noted below in an answer, if I put a while(true) around my DoSomethingWithThisText, that will work while debugging. However, it won't work when trying to run MyListener as a service, because Start will never get past the while(true) loop.
My listener service looks like this...
public class MyListener
{
private udpClient udpListener;
private int udpPort = 51551;
public void Start()
{
udpListener = new UdpClient(udpPort);
IPEndPoint listenerEndPoint = new IPEndPoint(IPAddress.Any, udpPort);
Byte[] message = udpListener.Receive(ref listenerEndPoint);
Console.WriteLine(Encoding.UTF8.GetString(message));
DoSomethingWithThisText(Encoding.UTF8.GetString(message));
}
}
My sender looks like this:
static void Main(string[] args)
{
IPAddress ipAddress = new IPAddress(new byte[] { 127, 0, 0, 1 });
int port = 51551;
//define some variables.
Console.Read();
UdpClient client = new UdpClient();
client.Connect(new System.Net.IPEndPoint(ipAddress, port));
Byte[] message = Encoding.UTF8.GetBytes(string.Format("var1={0}&var2={1}&var3={2}", new string[] { v1, v2, v3 }));
client.Send(message, message.Length);
client.Close();
Console.WriteLine(string.Format("Sent message");
Console.Read();
}
回答1:
You should call the receive from within a while or some other loop.
回答2:
I ended up using Microsoft's asynchronous methods, found here - BeginReceive and EndReceive .
Like Microsoft suggests, I call BeginReceive within my Start method like this:
UdpState s = new UdpState();
s.e = listenerEP;
s.u = udpListener;
udpListener.BeginReceive(new AsyncCallback(ReceiveCallback), s);
However, to get the listener to continue receiving messages, I call BeginReceive AGAIN within the ReceiveCallback function, recursively. This, of course, is a potential memory leak, but I've yet to encounter problems in my regression testing.
private void ReceiveCallback(IAsyncResult ar)
{
UdpClient u = (UdpClient)((UdpState)ar.AsyncState).u;
IPEndPoint e = (IPEndPoint)((UdpState)ar.AsyncState).e;
UdpState s = new UdpState();
s.e = e;
s.u = u;
udpListener.BeginReceive(new AsyncCallback(ReceiveCallback), s);
Byte[] messageBytes = u.EndReceive(ar, ref e);
string messageString = Encoding.ASCII.GetString(messageBytes);
DoSomethingWithThisText(messageString);
}
来源:https://stackoverflow.com/questions/7042288/udp-sending-receiving-in-net