VB.NET 写一段程序 创建一个TCP服务器
时间: 2023-12-23 13:03:01 浏览: 95
好的,以下是一个简单的VB.NET程序,用于创建一个TCP服务器:
```vb.net
Imports System.Net
Imports System.Net.Sockets
Public Class Form1
Private listener As TcpListener
Private client As TcpClient
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' 设置服务器IP地址和端口号
Dim ipAddress As IPAddress = IPAddress.Parse("127.0.0.1")
Dim port As Integer = 8080
Try
' 创建TCP监听器
listener = New TcpListener(ipAddress, port)
listener.Start()
' 等待客户端连接
client = listener.AcceptTcpClient()
' 连接成功,获取网络流对象
Dim stream As NetworkStream = client.GetStream()
' 发送消息到客户端
Dim message As String = "Hello, client!"
Dim data() As Byte = System.Text.Encoding.ASCII.GetBytes(message)
stream.Write(data, 0, data.Length)
' 关闭网络流和客户端
stream.Close()
client.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
' 关闭监听器
listener.Stop()
End Sub
End Class
```
这个程序创建了一个TCP监听器,并等待客户端连接。一旦客户端连接成功,它会发送一条消息,并关闭网络流和客户端。最后,它关闭监听器。你可以根据自己的需求修改代码。
阅读全文