3

I'm using this code to listening on port 9999 udp.

   Dim remoteSender As New IPEndPoint(IPAddress.Any, 0)
   client = New UdpClient(9999)
   Dim state As New UdpState(client, remoteSender)
   client.BeginReceive(New AsyncCallback(AddressOf DataReceived), state)

It work perfectly, i received event fired on sub DataReceived() if i send a udp message to 127.0.0.1:9999.

However, because i want to create a program that connect to udp server and waiting for response from server. So i inserted a connect command after create the socket.

   Dim remoteSender As New IPEndPoint(IPAddress.Any, 0)
   client = New UdpClient(9999)
   client.Connect("127.0.0.1", 1000) 
   Dim state As New UdpState(client, remoteSender)
   client.BeginReceive(New AsyncCallback(AddressOf DataReceived), state)

But i cannot receive any response from server when server send packet back to 127.0.0.1:9999, event is not fired like the first code.

So what wrong with my code ? I know both C# and Vb.net so the answer is all fine from both language.

Brian
  • 1,164
  • 1
  • 9
  • 27
LeDuc
  • 245
  • 2
  • 9

1 Answers1

1

http://msdn.microsoft.com/en-us/library/c4w4cta7(v=vs.110).aspx:

If you call the Connect method, any datagrams that arrive from an address other than the specified default will be discarded.

The datagrams you wish to receive are coming from a different address. Maybe the sender is using the LAN or WAN IP address instead of the loopback (127.0.0.1) address.

If you do not need the Connect call, just remove it.

usr
  • 168,620
  • 35
  • 240
  • 369