I am having problems doing asyncronous UDP with VB.Net 2003. I am trying
to be always listening on port 7000 for incoming UDP packets and process
them with OnReceive, and at any time send data through the socket on port
7000 to any dest.
When I call sock.BeginReceive, I am unable to use sock.BeginSendTo/SentTo,
but if I don't call it, I can send without getting the following error.
You can see this in test()
Unhandled Exception: System.NullReferenceException: Object reference not
set to an instance of an object.
at System.Net.OSSOCK.WSAGetOverlappedResult(IntPtr socketHandle, IntPtr
overlapped, UInt32& bytesTransferred, Boolean wait, IntPtr ignored) at
System.Net.Sockets.OverlappedAsyncResult.Completio nPortCallback(UInt32
errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
Can anyone give me advice on how to do this?
Thanks,
Dim sock As Socket
Dim buffer(1024 * 32) As Byte
Dim iasync As IAsyncResult
Sub test()
sock = New Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)
sock.Bind(New IPEndPoint(IPAddress.Parse("127.0.0.1"), 7000))
Dim d(1) As Byte : d(0) = 6
iasync = sock.BeginReceive(buffer, 0, buffer.Length, SocketFlags.Partial, New AsyncCallback(AddressOf OnReceive), Me)
sock.BeginSendTo(d, 0, 1, SocketFlags.None, New IPEndPoint(IPAddress.Parse("127.0.0.1"), 7001), New AsyncCallback(AddressOf OnSend), Me)
End Sub
Private Sub OnReceive(ByVal ar As IAsyncResult)
Dim bytesReceived As Integer = sock.EndReceive(ar)
Console.WriteLine("Data received")
End Sub
Sub OnSend(ByVal ar As IAsyncResult)
Console.WriteLine("Data was sent")
End Sub