创建UdpClient以读取传入数据 - VB.net

时间:2012-09-13 10:05:49

标签: vb.net udpclient

我有一个代码

*已编辑,包含整个代码段

 Dim receivingUdpClient As New UdpClient(20000)

   Dim RemoteIpEndPoint As New IPEndPoint(IPAddress.Any, 0)
   Try 

      Console.WriteLine("listening")

      Dim receiveBytes As [Byte]() = receivingUdpClient.Receive(RemoteIpEndPoint)

      Dim returnData As String = Encoding.ASCII.GetString(receiveBytes)

      Console.WriteLine(receiveBytes)

   Catch e As Exception
      Console.WriteLine(e.ToString())
   End Try 

但它给了我一个错误。

system.dll

中发生了类型system.net.sockets.socketexception的第一次机会异常

我真的很困惑这意味着什么。

2 个答案:

答案 0 :(得分:2)

尝试以下代码

Dim receivingUdpClient As New UdpClient(20000)
Dim RemoteIpEndPoint As New IPEndPoint(IPAddress.Any, 0)
Dim receiveBytes As [Byte]()
Dim returnData As String

while ("Your condition")

Try 

  Console.WriteLine("listening")

  receiveBytes = receivingUdpClient.Receive(RemoteIpEndPoint)

  returnData = Encoding.ASCII.GetString(receiveBytes)

  Console.WriteLine(receiveBytes)

Catch e As Exception
  Console.WriteLine(e.ToString())
End Try 

End While

答案 1 :(得分:0)

当调试应用程序时,只要遇到异常,就会通知调试器此时,应用程序被挂起,调试器决定如何处理异常。第一次通过这种机制称为“第一次机会”异常。

第一次机会异常消息通常并不意味着代码中存在问题。对于优雅处理异常的应用程序/组件,第一次机会异常消息让开发人员知道遇到并处理了异常情况。

对于没有异常处理的代码,调试器将收到第二次机会异常通知,并将以未处理的异常停止。

检查此链接: Handle Socket.ReceiveFrom with timeout without spamming console

对于您的情况,在循环内声明updClient将导致以下错误。

Only one usage of each socket address (protocol/network address/port) is normally permitted

您可以查看以下链接以获取解决方案。或者尝试在循环外声明它,看它是否有效。

http://blogs.msdn.com/b/dgorti/archive/2005/09/18/470766.aspx