2014-08-30 53 views
2

我使用此代码来侦听端口9999 udp。连接后无法接收UdpClient

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) 

它完美地工作,我收到了子DataReceived()如果我发送一个UDP消息127.0.0.1:9999触发的事件。

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

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

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

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

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

如果您不需要需要Connect调用,只需将其删除即可。

相关问题