Click here to Skip to main content
16,012,198 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm currently working on a UDP communication PC <-> ARM LM3S6965 (Luminary) through the Ethernet. On the PC there is a VB.net application that simulates a UDP server/client.

the message is broadcasted from Vb.net application to ARM LM3S6965 based device, and in return response is sent from ARM Device to vb.net application.

sometimes udpclient works fine and response is received, but sometimes receive UdpClient throws socket exception i.e. Only one usage of each socket address (protocol/network address/port) is normally permitted.

the line which throws exception is

VB
udpReceivingClient = New UdpClient(mnPort)


Complete VB.net Code is as follows
VB
Module mod_Search_UDP
Public mnPort As Int32 = 3040                                   'Port number to send/recieve data on
'Public Const msBroadcastAddress As String = "255.255.255.255"   'Sends data to all LOCAL listening clients, to send data over WAN you'll need to enter a public (external) IP address of the other client
'Dim endPoint As IPEndPoint = New IPEndPoint(msBroadcastAddress, mnPort)
Public udpReceivingClient As UdpClient                          'Client for handling incoming data
Public udpSendingClient As UdpClient                            'Client for sending data
Public receivingThread As Thread                                'Create a separate thread to listen for incoming data, helps to prevent the form from freezing up
Public mbiClosing As Boolean = False                            'Used to close clients if form is closing
Public mbiCloseRxClient As Boolean = False

Public Sub InitializeSender()
    Dim soc As Socket
    Dim lsPort As String
    Dim lnPort As Int32 = 3040
    Const lsBroadcastAdd As String = "255.255.255.255"
    'Dim endPoint As IPEndPoint = New IPEndPoint(msBroadcastAddress, mnPort)
    'udpSendingClient = New UdpClient(endPoint)
    udpSendingClient = New UdpClient(lsBroadcastAdd, lnPort)

    udpSendingClient.EnableBroadcast = True

    soc = udpSendingClient.Client
    lsPort = (CType(soc.LocalEndPoint, IPEndPoint).Port.ToString())
    mnPort = Convert.ToInt32(lsPort)
End Sub

Public Sub InitializeReceiver()
    'Create UdpClient class and bind it to the local port number provided
    'Try
    udpReceivingClient = New UdpClient(mnPort)
    'udpReceivingClient.EnableBroadcast = True
    mbiCloseRxClient = True
    'Catch ex As Exception
    '    MsgBox(ex.ToString)
    'End Try


    Dim start As ThreadStart = New ThreadStart(AddressOf MT_Receiver)
    receivingThread = New Thread(start)
    receivingThread.IsBackground = True
    receivingThread.Start()
End Sub

Public Sub MT_Receiver()

    Dim endPoint As IPEndPoint = New IPEndPoint(IPAddress.Any, mnPort)    'Listen for incoming data from any IP address on the specified port 
    Dim lbData() As Byte                                                'Buffer for storing incoming bytes
    Dim llRet As UInt16
    'udpListen.Poll(1000, Net.Sockets.SelectMode.SelectRead)
    While (True)                                                        'Setup an infinite loop
        If mbiClosing = True Then                                       'Exit sub if form is closing
            Exit Sub
        End If
        llRet = udpReceivingClient.Available
        If llRet > 0 Then
            lbData = udpReceivingClient.Receive(endPoint)                   'Receive incoming bytes
            'If udpListen.Available Then
            '    udpListen.Receive(lbData, 256, Net.Sockets.SocketFlags.None)
            'End If
            'If lbData Is Nothing Then
            'Else
            frmSearchUDP.MT_Validate_Msg(lbData)
        End If
    End While
End Sub
Public Sub MT_Send_UDP(ByVal lbTxBuffer() As Byte)
    InitializeSender()
    If mbiCloseRxClient = True Then
        receivingThread.Abort()
        udpReceivingClient.Client.Dispose()
        udpReceivingClient.Close()

    End If
    Try
        udpSendingClient.Send(lbTxBuffer, lbTxBuffer.Length)
    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try
    udpSendingClient.Client.Dispose()
    udpSendingClient.Close()
    InitializeReceiver()
    'Try
    '    udpReceivingClient.BeginReceive(AddressOf MT_RX_Callback, Nothing)
    'Catch ex As Exception
    '    MsgBox(ex.ToString)
    'End Try
End Sub
End Module
Posted
Comments
[no name] 9-Nov-14 10:10am    
When does it throw the exception, on the first or second connection? Have you tried debugging yet?
Sushantnaik21 9-Nov-14 23:26pm    
Very first connection but then sometimes it work fines and response is also received.
In debugging mode it doesnt throw any exception.
[no name] 10-Nov-14 9:36am    
Your sender is on the same port as your receiver. (May not be the issue.) Try changing the lnPort As Int32 = 3040 to 3041 and see if that resolves it, I can only conclude that the port is occasionally busy sending data when your receiver is also trying to access the same port. Put a break point on that line: Public Sub InitializeReceiver() and step through the code until it breaks hovering your mouse over the text.

Keep in mind when making these chat like apps, almost everything needs to be declared new, and almost everything should be set to run on their own threads. The way you wrote this, will hog your GUI down. Use multi threaded events.
Sushantnaik21 11-Nov-14 4:03am    
i dont understand how can i get exception when m closing sender udpclient before calling InitializeReceiver.
[no name] 11-Nov-14 10:10am    
You should have one client for sending and receiving. (Most people advise having two for UDP) You have two clients, one for receiving and one for sending, and both are operating on port 3040. (Change the port on one of them.) If the port is in use by another client, you may get an exception.

What you should do is have one defined client and set your receiver to run in a loop on a new thread to also avoid hanging your UI, and to avoid a clash when sending while receiving. As I've already suggested, set your receiver off on a new thread.

This SO answer might help you to compare code and methods.

Also move all the code in the commented out try block above this line: Dim start As ThreadStart = New ThreadStart(AddressOf MT_Receiver)
And put into your MT_Receiver thread - on the first line.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900