Foxtable(狐表)用户栏目专家坐堂 → 狐表怎么用TCP连接设备,输出设备的信息


  共有1290人关注过本帖树形打印复制链接

主题:狐表怎么用TCP连接设备,输出设备的信息

帅哥哟,离线,有人找我吗?
zhenghangbo
  1楼 | 信息 | 搜索 | 邮箱 | 主页 | UC


加好友 发短信
等级:一尾狐 帖子:477 积分:4569 威望:0 精华:0 注册:2018/2/7 14:30:00
狐表怎么用TCP连接设备,输出设备的信息  发帖心情 Post By:2024/8/9 9:44:00 [只看该作者]

设备ip地址xxx.xxx.xxx.xxx,端口:12345。代码案例如下:
Imports System.Net.Sockets
Imports System.Text

Public Class TCPClientExample
    Private client As TcpClient
    Private stream As NetworkStream

    Public Sub New()
        client = New TcpClient()
        stream = Nothing
    End Sub

    Public Sub Connect(host As String, port As Integer)
        Try
            client.Connect(host, port)
            stream = client.GetStream()
            Console.WriteLine("Connected to server.")
            ReceiveData() ' 开始接收数据
        Catch ex As Exception
            Console.WriteLine("Connection failed: " & ex.Message)
        End Try
    End Sub

    Private Async Sub ReceiveData()
        Dim buffer(1024) As Byte
        Dim received As Integer

        While True
            Try
                received = Await stream.ReadAsync(buffer, 0, buffer.Length)
                Dim data As String = Encoding.UTF8.GetString(buffer, 0, received)
                Console.WriteLine("Received from server: " & data)
            Catch ex As Exception
                Console.WriteLine("Receive failed: " & ex.Message)
                Exit While
            End Try
        End While
    End Sub

    Public Sub SendData(message As String)
        If stream IsNot Nothing Then
            Dim data As Byte() = Encoding.UTF8.GetBytes(message)
            Try
                stream.Write(data, 0, data.Length)
                Console.WriteLine("Sent to server: " & message)
            Catch ex As Exception
                Console.WriteLine("Send failed: " & ex.Message)
            End Try
        Else
            Console.WriteLine("Not connected to server.")
        End If
    End Sub

    Public Sub Disconnect()
        If stream IsNot Nothing Then
            stream.Close()
        End If
        If client IsNot Nothing Then
            client.Close()
        End If
    End Sub
End Class

Module Program
    Sub Main(args As String())
        Dim client As New TCPClientExample()

        client.Connect("localhost", 12345) ' 请替换为实际的服务端地址和端口号

        Console.WriteLine("Press Enter to send a message...")
        While Not Console.KeyAvailable
            If Console.KeyAvailable Then
                Dim input As String = Console.ReadLine()
                client.SendData(input)
            End If
        End While

        client.Disconnect()
        Console.WriteLine("Disconnected.")
        Console.ReadKey()
    End Sub
End Module


 回到顶部
帅哥哟,离线,有人找我吗?
有点蓝
  2楼 | 信息 | 搜索 | 邮箱 | 主页 | UC


加好友 发短信
等级:超级版主 帖子:110544 积分:562604 威望:0 精华:9 注册:2015/6/24 9:21:00
  发帖心情 Post By:2024/8/9 9:49:00 [只看该作者]


 回到顶部