我在VB.NET(2010)中有一项服务,它正在异步接收带有UDPClient.BeginReceive的UDP数据包。 一切正常,我能够收到分组数据 - 但我无法获得发送方(或远程)端点。
有一个CallBack例程正在接收一个IAsyncResult对象,该对象由System.net.sockets.OverlappedAsyncResult表示,其中属性SocketAddress是一个字节数组,其中是发送方端口和发送方IP地址。 但它只能在调试时访问 - 我在异步回调例程中使用断点。
我无法将IAsyncResult强制转换为OverlappedAsyncResult,而且我无法在设计时访问套接字地址。它给了我一个错误,意味着没有找到对象,也无法声明它。
我正在附加一个我用它的类供参考。有没有更好的方法,或者我可以获得发件人IP?
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Public Class UDPInterface
Implements IDisposable
#Region "IDisposable Support"
Private disposedValue As Boolean ' To detect redundant calls
' IDisposable
Protected Overridable Sub Dispose(disposing As Boolean)
If Not Me.disposedValue Then
If disposing Then
' TODO: dispose managed state (managed objects).
End If
' TODO: free unmanaged resources (unmanaged objects) and override Finalize() below.
' TODO: set large fields to null.
End If
Me.disposedValue = True
End Sub
' TODO: override Finalize() only if Dispose(ByVal disposing As Boolean) above has code to free unmanaged resources.
'Protected Overrides Sub Finalize()
' ' Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above.
' Dispose(False)
' MyBase.Finalize()
'End Sub
' This code added by Visual Basic to correctly implement the disposable pattern.
Public Sub Dispose() Implements IDisposable.Dispose
' Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above.
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
#End Region
Private _EP As UdpClient
Private _RemIPEP As System.Net.IPEndPoint
Private _Port As Integer
Public Sub New(Port As Integer)
_Port = Port
_RemIPEP = New IPEndPoint(System.Net.IPAddress.Any, Port)
_EP = New UdpClient
_EP.Client.Bind(_RemIPEP)
_EP.BeginReceive(AddressOf Receive, _EP)
End Sub
Public Sub SendPacket(Bytes As Byte())
_EP.Send(Bytes, Bytes.Length, New IPEndPoint(System.Net.IPAddress.Broadcast, _Port))
End Sub
Private Sub Receive(rec As IAsyncResult)
Dim RX As Byte() = _EP.EndReceive(rec, _RemIPEP)
Debug.Print(Encoding.ASCII.GetString(RX))
_EP.BeginReceive(AddressOf Receive, _EP)
RaiseEvent PacketReceived(RX)
End Sub
Public Event PacketReceived(Bytes As Byte())
End Class