VB.NET 写一段程序 用TCP创建一个服务器,帧听多个端口数据,并发送对应端口数据到客户端
时间: 2024-02-25 12:53:32 浏览: 177
好的,以下是一个简单的VB.NET程序,用于创建一个TCP服务器,监听多个端口,并将对应端口的数据发送到客户端:
```vb.net
Imports System.Net
Imports System.Net.Sockets
Imports System.Threading
Public Class Form1
Private listeners As List(Of TcpListener)
Private clients As List(Of TcpClient)
Private threads As List(Of Thread)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' 创建TCP监听器
listeners = New List(Of TcpListener)()
listeners.Add(New TcpListener(IPAddress.Any, 8080))
listeners.Add(New TcpListener(IPAddress.Any, 8081))
listeners.Add(New TcpListener(IPAddress.Any, 8082))
' 启动监听器
clients = New List(Of TcpClient)()
threads = New List(Of Thread)()
For i As Integer = 0 To listeners.Count - 1
listeners(i).Start()
threads.Add(New Thread(AddressOf Listen))
threads(i).Start(i)
Next
End Sub
Private Sub Listen(ByVal index As Object)
Dim port As Integer = 8080 + index
Dim listener As TcpListener = listeners(index)
Dim client As TcpClient
While True
Try
' 等待客户端连接
client = listener.AcceptTcpClient()
' 连接成功,添加到客户端列表
clients.Add(client)
' 获取网络流对象
Dim stream As NetworkStream = client.GetStream()
' 接收客户端消息
Dim data(1024) As Byte
Dim bytes As Integer = stream.Read(data, 0, data.Length)
Dim message As String = System.Text.Encoding.ASCII.GetString(data, 0, bytes)
' 发送消息到客户端
Dim response As String = "Port " & port & ": " & message
Dim responseData() As Byte = System.Text.Encoding.ASCII.GetBytes(response)
stream.Write(responseData, 0, responseData.Length)
' 关闭网络流和客户端
stream.Close()
client.Close()
clients.Remove(client)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End While
End Sub
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
' 关闭监听器和客户端
For i As Integer = 0 To listeners.Count - 1
listeners(i).Stop()
threads(i).Abort()
Next
For Each client As TcpClient In clients
client.Close()
Next
End Sub
End Class
```
这个程序创建了三个TCP监听器,分别监听8080、8081和8082三个端口。它使用多线程来同时监听三个端口,并将对应端口的数据发送给客户端。一旦客户端连接成功,它会接收客户端的消息,并发送一个回复,然后关闭网络流和客户端。当程序关闭时,它会关闭所有监听器和客户端。你可以根据需要修改代码。
阅读全文