连接后UdpClient无法接收

时间:2014-08-30 09:15:17

标签: .net vb.net udpclient

我正在使用此代码侦听端口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)

它工作得很好,如果我发送一条udp消息到127.0.0.1:9999,我收到了在子DataReceived()上触发的事件。

但是,因为我想创建一个连接到udp服务器并等待服务器响应的程序。所以我在创建套接字后插入了一个connect命令。

   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)

但是当服务器将数据包发送回127.0.0.1:9999时,我无法从服务器收到任何响应,事件不像第一个代码那样被触发。

我的代码出了什么问题?我知道C#和Vb.net,所以两种语言的答案都很好。

1 个答案:

答案 0 :(得分:1)

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

  

如果您调用Connect方法,将丢弃从指定默认值以外的地址到达的任何数据报。

您希望收到的数据报来自不同的地址。也许发件人使用LAN或WAN IP地址而不是环回(127.0.0.1)地址。

如果您需要 Connect来电,请将其删除。

相关问题