E_Blue
E_Blue

Reputation: 1151

UdpClient can act as server?

I tried for about two weeks a lot of differents codes but none works as I espect.

I just need to receive packets on a defined port and answer to that packet to the origin port of the remote IP

I.E. I'm listening on port 8090 and receive a packet from remote port 6508(sourceport) I need to deliver the answer from 8090(local outgoing port) to 6508(remote incoming port) without stop listen another incoming data from another remote host.

The problem is that, with UDPClient, I can't use the same port that I'm using to listen to answer.

The best approach that I get is to receive an answer to only one remote host(the first one).

So I'm wondering if it's possible to use the same UDPClient to answer an receive from different remote host.

I'm feeling a bit frustrated about.

Can you guide me please?


New info I ran some test and the receive thread works ok and receive data from any remote host until send an answer on the following code.

Private Sub UdpSend(ByVal txtMessage As String)
    Dim pRet As Integer
    GLOIP = IPAddress.Parse(IpRemotaLbl.Text)
    GLOINTPORT = PuertoEscuchaLbl.Text
    MyUdpClient.Connect(GLOIP, DstPort) 'Can be here the error?
    bytCommand = Encoding.ASCII.GetBytes(txtMessage)
    pRet = MyUdpClient.Send(bytCommand, bytCommand.Length)

    PrintLog("No of bytes send " & pRet)
End Sub

It seems like when it connects to a remote host stop listening any other remote host.

Upvotes: 1

Views: 134

Answers (1)

E_Blue
E_Blue

Reputation: 1151

Solution thanks to @LokiSinclair

UDP SocketException - Only one usage of each socket address is normally permitted

Private Sub UdpSend(ByVal txtMessage As String)
    Dim pRet As Integer
    GLOIP = IPAddress.Parse(IpRemotaLbl.Text)

    Using UdpSender As New System.Net.Sockets.UdpClient()
        Dim RemoteEndPoint = New System.Net.IPEndPoint(0, 8090)
        UdpSender.ExclusiveAddressUse = False
        UdpSender.Client.SetSocketOption(Net.Sockets.SocketOptionLevel.Socket, Net.Sockets.SocketOptionName.ReuseAddress, True)
        UdpSender.Client.Bind(RemoteEndPoint)
        UdpSender.Connect(GLOIP, DstPort) 'GLOIP Null?
        bytCommand = Encoding.ASCII.GetBytes(txtMessage)
        pRet = UdpSender.Send(bytCommand, bytCommand.Length)
    End Using

    PrintLog("No of bytes send " & pRet)
End Sub

Upvotes: 1

Related Questions