1

我想从多个 tcp/ip 设备读取数据。我想在 vb.net 或 c# 中创建一个应用程序,它将一次与多个设备进行通信。如何一次连接多个设备?IP 地址为 xxx.xx.xx.100、xxx.xx.xx.101、xxx.xx.xx.102、xxx.xx.xx.103、xxx.xx.xx.104、xxx.xx.xx.105等和相同的端口号 8000。我正在向连接的设备发送请求,设备给出响应。我能够从设备读取数据。用于检查连接状态和以 100 毫秒间隔轮询的计时器。如何一次连接和轮询多个设备而不阻塞其他设备?请帮我。

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
4

0 回答 0