2009/10/07

KB: You must call the Bind method before performing this operation.

I got this error message: "You must call the Bind method before performing this operation." when using the UDP protocol to communicate with another application. Here is the simplified code
.......
IPAddress serverIP = IPAddress.Parse("xx.xx.xx.xx");
IPEndPoint serverEP = new IPEndPoint(serverIP, 12345);
UdpClient client = new UdpClient();

//start listening
client.BeginReceive(new AsyncCallback(ReceiveCallback), serverEP); //here causes the problem
//send message to server and wait for response
client.Send(Encoding.UTF8.GetBytes("Hello"), "Hello".Length, serverEP);
.....
After spending so many hours on this issue, I finally figure out what the problem is.
The error message already mentioned that you must Bind first! Therefore, I changed the order of the listening & sending, and it works! Here is the code that works
.......
IPAddress serverIP = IPAddress.Parse("xx.xx.xx.xx");
IPEndPoint serverEP = new IPEndPoint(serverIP, 12345);
UdpClient client = new UdpClient();

//send message to server and wait for response
client.Send(Encoding.UTF8.GetBytes("Hello"), "Hello".Length, serverEP);
//start listening
client.BeginReceive(new AsyncCallback(ReceiveCallback), serverEP);
.....
This may not be the case that you encounter. It just one of the many possibilities to solve the issue.

7 comments:

  1. You are absolutely right

    ReplyDelete
  2. please post VB.NET Code.

    ReplyDelete
  3. You can try the "Convert C# to VB.Net" link from my External Links section at the bottom right corner.

    ReplyDelete
  4. Thanks for Solution but this not work in .NET Framework 3.5 .

    In my Application, "You must call the Bind method before performing this operation." error generated how it solve???

    please give me a solution.

    ReplyDelete
  5. ?????? where is solution? ????????

    ReplyDelete
  6. If this doesn't resolve your problem, you probably have to Google it for other solutions.

    ReplyDelete
  7. The correct solution is documented here:
    http://msdn.microsoft.com/en-us/library/system.net.sockets.udpclient.aspx

    You must use the constructor that accepts (int)port on the UDPClient that is receiving the message.

    ReplyDelete