vb.net tcp 服务器举例
时间: 2024-11-12 07:08:49 浏览: 20
在VB.NET中,创建TCP服务器的一个基本例子通常是使用`TcpListener`类。以下是简单的步骤和代码示例:
```vb
Imports System.Net
Imports System.Net.Sockets
Public Class TcpServer
Private Sub StartServer()
' 创建一个监听器,绑定到特定端口
Dim listener As New TcpListener(IPAddress.Any, 8080)
' 开始监听连接请求
listener.Start()
Console.WriteLine("TCP Server started on port " & listener.LocalEndpoint.Port)
' 当有新的客户端连接时...
While True
' 获取一个新的网络流
Dim client As TcpClient = listener.AcceptTcpClient()
' 创建一个线程来处理每个客户端连接
Dim clientThread As New Thread(New ParameterizedThreadStart(AddressOf HandleClient))
clientThread.Start(client)
End While
End Sub
' 客户端处理方法
Private Shared Sub HandleClient(ByVal client As TcpClient)
Try
' 创建一个网络流来读取和写入数据
Dim networkStream As NetworkStream = client.GetStream()
Dim buffer(1024) As Byte
Dim receivedData As String = ""
' 接收客户端发送的数据
Do
Dim bytesRead As Integer = networkStream.Read(buffer, 0, buffer.Length)
If bytesRead > 0 Then
receivedData += Encoding.ASCII.GetString(buffer, 0, bytesRead)
Else
Exit Do
End If
Loop
Console.WriteLine("Received from client: " & receivedData)
' 发送响应给客户端
networkStream.Write(Encoding.ASCII.GetBytes("Hello, client!"), 0, "Hello, client!".Length)
' 关闭连接
client.Close()
Catch ex As Exception
Console.WriteLine("Error: " & ex.Message)
Finally
' 确保清理资源
client.Close()
End Try
End Sub
Public Shared Sub Main()
' 启动服务器
Dim server As New TcpServer()
Threading.Thread.CurrentThread.IsBackground = True
server.StartServer()
End Sub
End Class
```
这段代码首先启动了一个TCP服务器监听8080端口。每当有新客户端连接时,它会在单独的线程上创建一个`HandleClient`方法来处理接收到的消息,向客户端发送响应,并关闭连接。
阅读全文