vb.net tcp ip client server example

VB.NET提供了许多构建TCP/IP客户端和服务器应用程序的功能。下面是一个简单的VB.NET TCP/IP客户端/服务器示例:

服务器端示例代码:

Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Module Module1
    Sub Main()
        Dim listener As New TcpListener(IPAddress.Any, 8888)
        listener.Start()
        Console.WriteLine("服务器启动,等待连接...")
        While True
            Dim client As TcpClient = listener.AcceptTcpClient()
            Dim stream As NetworkStream = client.GetStream()
            Dim data(1024) As Byte
            Dim response As String = String.Empty
            Dim bytes As Int32 = stream.Read(data, 0, data.Length)
            response = Encoding.ASCII.GetString(data, 0, bytes)
            Console.WriteLine("接收到客户端消息: " + response)
            Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes("服务器已收到您的消息!")
            stream.Write(sendBytes, 0, sendBytes.Length)
            client.Close()
        End While
    End Sub
End Module

客户端示例代码:

Imports System.Net.Sockets
Imports System.Text
Module Module1
    Sub Main()
        Dim client As New TcpClient()
        client.Connect("127.0.0.1", 8888)
        Console.WriteLine("连接到服务器...")
        Dim stream As NetworkStream = client.GetStream()
        Dim message As String = "Hello, Server!"
        Dim data As [Byte]() = Encoding.ASCII.GetBytes(message)
        stream.Write(data, 0, data.Length)
        Console.WriteLine("发送消息给服务器: " + message)
        data = New [Byte](1024) {}
        Dim responseData As [String] = [String].Empty
        Dim bytes As Int32 = stream.Read(data, 0, data.Length)
        responseData = Encoding.ASCII.GetString(data, 0, bytes)
        Console.WriteLine("接收到服务器的响应: " + responseData)
        client.Close()
    End Sub
End Module

上面的代码演示了如何在VB.NET中实现一个简单的TCP/IP客户端和服务器应用程序。这些示例可以作为您构建更复杂应用程序的基础。需要注意的是,这只是一个示例,实际使用中需要根据具体需求进行适当的修改和调整。

  •