Hi all.
My programming skills are very basic. I am trying to make a client/server communication program using UDP in Visual Basic Express 2008.
It is a simple receiver for messages another app I've wrote sends.
The problem is that it works fine when it receives from 1 computer. If I have 2 or more computers sending, it throws exceptions quite regularly in the Invoke line.
Here is the code:
<pre lang="vb">
Private Sub MigraReceiver_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
StartListening()
End sub
Private Sub ProcessPacket(ByVal ar As IAsyncResult)
Dim Data As Byte()
SyncLock UDPReadLock
Try
Data = ListenSocket.EndReceive(ar, New System.Net.IPEndPoint(System.Net.IPAddress.Any, 0))
Catch ex As Exception
' Handle any exceptions here
Finally
Try
UDPSyncResult = ListenSocket.BeginReceive(AddressOf ProcessPacket, UDPState)
Catch ex As Exception
' Do nothing
End Try
End Try
End SyncLock
' Only attempt to process if we received data
If Data.Length > 0 Then
Dim Thread As New System.Threading.Thread(AddressOf SetText)
Thread.Start(System.Text.Encoding.Unicode.GetString(Data))
'SetText(System.Text.Encoding.Unicode.GetString(Data))
End If
End Sub
Private Sub StartListening()
Try
ListenSocket = New System.Net.Sockets.UdpClient
ListenSocket.Client.SetSocketOption(Net.Sockets.SocketOptionLevel.Socket, Net.Sockets.SocketOptionName.ReuseAddress, True)
ListenSocket.Client.Bind(New System.Net.IPEndPoint(System.Net.IPAddress.Any, listenPort))
UDPSyncResult = ListenSocket.BeginReceive(AddressOf ProcessPacket, UDPState)
Catch ex As Exception
'Handle an exception
End Try
End Sub
Private Delegate Sub SetTextDelegate(ByVal [text] As String)
Private Sub SetText(ByVal text As String)
Dim espera_ordem As Integer = 0
If Me.TabControl1.InvokeRequired Then
'THIS IS WHERE IT THROWS THE EXCEPTION:
Me.TabControl1.Invoke(New SetTextDelegate(AddressOf SetText), New Object() {text})
Else
'Does GUI updates.
End if
End Sub
It throws an exception 'Array out of bounds' in the
Me.TabControl1.Invoke(New SetTextDelegate(AddressOf SetText), New Object() {text})
line.
I've been trying, testing and searching for 3 days without success :(
It seems the problem occurs when I receive several packets in a short time.
Any help would be appreciated. Thanks.
Regards,
Mike