Is it possible to connect two UdpClient to the same local socket?

2

I need to have a thread listening on a port UDP specific to be designated by the user and the ACK should be sent from the same port to the port from which it is listening on the local server but at the push of a button on the GUI of the server; that is, I can not respond at the moment.

The problem is that when I try to answer, being the first socket Bindeado to this specific port does not allow me to create the new UdpClient to send a response to the last IP.

I've already tried putting the value

.ExclusiveAddressUse = False 

of the first socket, the listener, as well as

.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, True)

I've tried a dozen examples that I found but they all have the same problem, to get perfect, but when you add code for a second socket it does not work anymore.

I do not know what else to do.

The following code sends and receives but only the first IP that connects. I tried to disconnect after sending but I get error 100057.

Imports System.Net.Sockets
Imports System.Net
Imports System.Text
Imports System.Threading

#Region "UDP Receive variables"
    Public RemoteIpEndPoint As New System.Net.IPEndPoint(System.Net.IPAddress.Any, 5000)
    Public ThreadReceive As System.Threading.Thread
    Dim SocketNO As Integer
    Dim UdpOpen As Boolean = False
    Dim DstPort As Integer = 0
    Private permission As SocketPermission
    Dim LastIpRemota As String = ""
    Dim LastPort As String = ""
#End Region

#Region "UDP Send variables"
    Dim GLOIP As IPAddress
    Dim GLOINTPORT As Integer
    Dim bytCommand As Byte() = New Byte() {}
    Dim MyUdpClient As New UdpClient()
#End Region

Private Sub StartUdpReceiveThread(ByVal Port As Integer)
      Dim UdpAlreadyOpen As Boolean = False

      Try
          'If Not UdpOpen Then
          permission = New SocketPermission(NetworkAccess.Accept, TransportType.Udp, "", SocketPermission.AllPorts)
          permission.Demand()
          MyUdpClient = New UdpClient()
          MyUdpClient.ExclusiveAddressUse = False
          MyUdpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, True)
          ''****** Codigo agregado para hacer Bind ******
          Dim LocalEnPoint As EndPoint
          Dim LocalIP As System.Net.IPAddress
          LocalIP = System.Net.IPAddress.Parse("0.0.0.0")
          LocalEnPoint = New System.Net.IPEndPoint(LocalIP, Port)
          MyUdpClient.Client.Bind(LocalEnPoint)
          ''***********************************************

          UdpAlreadyOpen = True

          '  End If

          ThreadReceive = New System.Threading.Thread(AddressOf UdpReceive)
          ThreadReceive.IsBackground = True

          ThreadReceive.Start()
          UdpOpen = True

          If UdpAlreadyOpen Then 'Solo se imprime la primera vez
              PrintLog(String.Format("Puerto UDP {0} abierto, esperando datos...", Port.ToString))
          End If
      Catch ex As Exception
          PrintLog(ex.Message)
          PrintLog(ex.StackTrace)
      End Try
End Sub

Private Sub UdpReceive()
    Dim ACK As String = ""
    Dim receiveBytes As [Byte]() = MyUdpClient.Receive(RemoteIpEndPoint) ' aqui se traba al salir, queda esperando datos fuera del codigo

    DstPort = RemoteIpEndPoint.Port
    IpRemota(RemoteIpEndPoint.Address.ToString)

    Dim BitDet As BitArray
    BitDet = New BitArray(receiveBytes)
    Dim strReturnData As String = System.Text.Encoding.ASCII.GetString(receiveBytes)

    PrintLog("From: " & IpRemotaLbl.Text & ":" & PuertoEscuchaLbl.Text & " - " & strReturnData)
    ACK = "OK 12345" & vbCrLf  'AnswersProcessor(strReturnData)

    If ACK.Length > 7 Then
        MyUdpClient.Connect(RemoteIpEndPoint)
        MyUdpClient.Send(Encoding.ASCII.GetBytes(ACK), ACK.Length)
        'MyUdpClient.Client.Disconnect(True) 'Da error 10057
    End If

    If UdpOpen Then
        StartUdpReceiveThread(5000)
    End If
    ' MyUdpClient.Client.LingerState = True

End Sub

Private Sub UdpSend(ByVal txtMessage As String)
 'Esta rutina da error porque el puerto ya esta siendo usado por el otro UdpClient

    Dim pRet As Integer
    GLOIP = IPAddress.Parse(IpRemotaLbl.Text)
    GLOINTPORT = PuertoEscuchaLbl.Text
    MyUdpClient.Connect(GLOIP, DstPort)
    bytCommand = Encoding.ASCII.GetBytes(txtMessage)
    pRet = MyUdpClient.Send(bytCommand, bytCommand.Length)
    'Console.WriteLine("No of bytes send " & pRet)
    PrintLog("No of bytes send " & pRet)
End Sub

Maybe on some variable because I already modified it a lot of times.

    
asked by E_Blue 19.12.2016 в 20:45
source

1 answer

0

Without having any idea of vb.net, I think you are focusing the problem poorly.

Why do not you use the thread that you also listen to send?

That first thread (which we will call SERVER) should listen on the UDP port you indicate and on another socket or pipe or < em> puerto or whatever you call it in vb.net, in which you listen to the commands of a second thread, which will be responsible for the GUI (we call that thread GUI).

When the button is pressed, GUI sends a packet to SERVER, which in turn sends the data you want through the port in question.

    
answered by 19.12.2016 в 21:00