The C # chat application freezes when the code is executed


so I have been working on my chat application in c# as a windows form application and when this code to receive data has to be executed the program freezes.

Anyone help me please, finding out whats wrong about this. As a console application it works.

UdpClient udpClient = new UdpClient(Convert.ToInt32(textPort.Text));

            IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);

            Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
            string returnData = Encoding.ASCII.GetString(receiveBytes);

            textMsg.Text = returnData.ToString();

Your program is frozen because the UdpClient class's Receive(...) method is blocking.

That is to say, it will stop at that point of execution and not allow the thread/process it is in to continue until it receives a single UDP packet. This includes the UI unless you put this in a separate thread or us an asynchronous communication model.

If you want to handle communications asynchronously, check out the BeginReceive(...) method.

And here is some example code (Originally, I was using this codestraight from Microsoft. However, it was missing the definition for UdpState. After some teeth gnashing, I figured out you had to create it to pass your own state in so the asynchronous model would work as expected. The example has been updated and compiles in VS2008, .Net 3.5):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace ConsoleApplication1
    class UdpState
        public IPEndPoint e = null;
        public UdpClient u = null;

    class Program
        public static bool messageReceived = false;

        public static void ReceiveCallback(IAsyncResult ar)
            UdpClient u = (UdpClient)((UdpState)(ar.AsyncState)).u;
            IPEndPoint e = (IPEndPoint)((UdpState)(ar.AsyncState)).e;

            Byte[] receiveBytes = u.EndReceive(ar, ref e);
            string receiveString = Encoding.ASCII.GetString(receiveBytes);

            Console.WriteLine("Received: {0}", receiveString);
            messageReceived = true;

        public static void ReceiveMessages(int listenPort)
            // Receive a message and write it to the console.
            IPEndPoint e = new IPEndPoint(IPAddress.Any, listenPort);
            UdpClient u = new UdpClient(e);

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

            Console.WriteLine("listening for messages");
            u.BeginReceive(new AsyncCallback(ReceiveCallback), s);

            // Do some work while we wait for a message. For this example,
            // we'll just sleep
            while (!messageReceived)

        static void Main(string[] args)

Was this helpful?