How to connect multiple IP addresses with same port number using TCP/IP client?

柔情痞子 提交于 2019-12-11 06:39:49

问题


I want to read data from multiple tcp/ip devices. I want to create an application in vb.net or c# which will communicate with multiple devices at a time. How to connect multiple devices at a time? IP addresses as xxx.xx.xx.100, xxx.xx.xx.101, xxx.xx.xx.102, xxx.xx.xx.103, xxx.xx.xx.104, xxx.xx.xx.105, etc and same port number 8000. I am sending request to connected device & the device gives the response. I am able to read data from a device. Timer used for checking connection status & polling with 100ms interval. How to connect & polling multiple devices at a time without blocking to other? Please help me.

Dim tcpclient As System.Net.Sockets.TcpClient
Dim serverStream As NetworkStream
Dim outStream As Byte()
Dim inStream(8192) As Byte
Dim sendstring As String
Dim client_connected as Boolean = False

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs)    Handles Timer1.Tick

    // interval 100ms
    If client_connected = False Then
        tcpclient_1 = New System.Net.Sockets.TcpClient
        tcpclient_1.SendTimeout = 10
        tcpclient_1.ReceiveTimeout = 10

        Try
            tcpclient_1.Connect("xxx.xx.xx.100", 8000)
            client_connected = True
            label1.text = "connected"

            sendstring = "xxxx"
            serverStream = tcpclient_1.GetStream()
            outStream = System.Text.Encoding.Default.GetBytes()
            serverStream.Write(outStream, 0, outStream.Length)
            serverStream.Flush()

            Dim responseData As [String] = [String].Empty
            responseData = serverStream.Read(inStream, 0, _
                           CInt(tcpclient_1.ReceiveBufferSize))
            label2.text = responseData 
        Catch ex As Exception
            client_connected = False
            label1.text = "disconnected"
        End Try
    Else
        label1.text = "connected"
    End If
End Sub

来源:https://stackoverflow.com/questions/17371362/how-to-connect-multiple-ip-addresses-with-same-port-number-using-tcp-ip-client

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!