UDP Bind Method

18,204

Solution 1

You need to tell the udpclient what port to listen to. The IPEndpoint you pass the receive method can be set to anything you like, since it gets populated with the senders details. It does not direct the udpclient to listen to port 11000. In affect you're trying to listen to port 0, which instructs the udpclient to pick it's own port.

Have a look at http://msdn.microsoft.com/en-us/library/system.net.sockets.udpclient.receive.aspx

You'll see the constructor is called with the port to listen on.

Solution 2

I believe you need to call Bind on the listening server first:

udpServer.Client.Bind(new IPEndPoint(IPAddress.Any, 11000));
Share:
18,204
user112016322
Author by

user112016322

Updated on June 18, 2022

Comments

  • user112016322
    user112016322 almost 2 years

    I am trying to set up a UDP communication link between 2 computers. One computer is running the client app and the other is running the server app. The client app gives the error:

    You must call the Bind method before performing this operation.

    Here is my code below for the client below and I have commented where the error occurs:

     public delegate void ShowMessage(string message);
        UdpClient udpClient = new UdpClient();
        Int32 port = 11000;
        public ShowMessage myDelegate;
        Thread thread;
    
    
    private void Form1_Load(object sender, EventArgs e)
        {
            thread = new Thread(new ThreadStart(ReceiveMessage));
            thread.IsBackground = true;
            thread.Start();
        }
    
    
        private void ReceiveMessage()
        {
            while (true)
            {
                IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, port);
    
                //Error on this line
                byte[] content = udpClient.Receive(ref remoteIPEndPoint);
    
                if (content.Length > 0)
                {
                    string message = Encoding.ASCII.GetString(content);
    
    
                    this.Invoke(myDelegate, new object[] { message });
                }
    
            }
    
        }
    

    Any help would be greatly appreciated.

    source -> http://lamahashim.blogspot.com/2009/06/using-c-udpclient-send-and-receive.html