UDP Sending / Receiving in .NET

I am new to UDP. Using the test environment, I can send / receive one UDP message. However, I am trying to figure out how to get multiple UDP messages. I would like the MyListener service to receive UDP packets all day when I send them. I appreciate any help.

PS - As indicated in the answer below, if I put some (true) time around my DoSomethingWithThisText, this will work during debugging. However, when you try to start MyListener as a service, it will not work, because Start will never pass 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 is as follows:

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();
}
0
source share
2 answers

Microsoft, - BeginReceive EndReceive.

Microsoft, BeginReceive "" :

UdpState s = new UdpState();
s.e = listenerEP;
s.u = udpListener;

udpListener.BeginReceive(new AsyncCallback(ReceiveCallback), s);

, , BeginReceive AGAIN ReceiveCallback, . , , , .

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);
}
+1

- .

+2

All Articles