写一个vb.net的tcp/socket 服务器和客户端都包涵的程序
时间: 2024-10-02 12:01:16 浏览: 45
VB.NET TCP/IP Server and Client
在VB.NET中编写TCP套接字服务器和客户端程序,你需要了解基本的网络编程原理,并熟悉如何使用System.Net命名空间下的TcpClient和TcpServer类。这里是一个简单的示例:
**服务器端(Server.vb):**
```vb.net
Imports System.Net
Imports System.IO
Public Class ServerForm
Private server As TcpListener
Private client As TcpClient
Public Sub New()
InitializeComponent()
' 创建监听器并开始监听
Dim ip As String = "localhost" ' 可修改为你希望监听的IP地址
Dim port As Integer = 12345 ' 可修改为你希望的端口号
server = New TcpListener(IPAddress.Parse(ip), port)
server.Start()
' 监听新的连接请求
AddHandler server.Accepted, AddressOf AcceptClient
End Sub
Private Sub AcceptClient(sender As Object, e As NetworkStreamEventArgs)
' 当有新客户端连接时,创建一个新的线程处理请求
Dim newClient As TcpClient = e.ConnectedSocket
Dim stream As NetworkStream = newClient.GetStream()
Dim buffer(1024) As Byte
' 在新线程中处理客户端通信
Dim clientThread As New Thread(AddressOf HandleClientCommunication)
clientThread.Start(stream)
End Sub
Private Sub HandleClientCommunication(ByVal stream As NetworkStream)
Try
' 读取和发送数据
While True
Dim bytesRead As Integer = stream.Read(buffer, 0, buffer.Length)
If bytesRead > 0 Then
Dim message As String = Encoding.ASCII.GetString(buffer, 0, bytesRead)
Console.WriteLine("Received from Client: " & message)
stream.Write(Encoding.ASCII.GetBytes("Message received"), 0, message.Length)
Else
' 客户端断开连接,关闭流
stream.Close()
Exit While
End If
End While
Catch ex As Exception
Console.WriteLine("Error: " & ex.Message)
Finally
' 关闭客户端连接
stream.Close()
client = Nothing
End Try
End Sub
End Class
```
**客户端(Client.vb):**
```vb.net
Imports System.Net
Imports System.IO
Public Class ClientForm
Private client As TcpClient
Private stream As NetworkStream
Public Sub New()
InitializeComponent()
' 连接到服务器
Dim ipAddress As String = "localhost" ' 修改为你服务器的实际IP地址
Dim port As Integer = 12345 ' 修改为你服务器使用的端口号
client = New TcpClient()
client.Connect(ipAddress, port)
' 获取连接后的网络流
stream = client.GetStream()
' 发送一条消息到服务器
Dim sendMessage As String = "Hello Server"
SendData(Encoding.ASCII.GetBytes(sendMessage))
' 接收服务器响应
ReceiveData()
End Sub
Private Sub SendData(ByVal data As Array)
Dim bytes Sent As Integer = stream.Write(data, 0, data.Length)
Console.WriteLine("Sent: " & Encoding.ASCII.GetString(data))
End Sub
Private Sub ReceiveData()
Dim buffer(1024) As Byte
Dim bytesRead As Integer = stream.Read(buffer, 0, buffer.Length)
If bytesRead > 0 Then
Dim message As String = Encoding.ASCII.GetString(buffer, 0, bytesRead)
Console.WriteLine("Received from Server: " & message)
Else
' 服务器断开连接
MessageBox.Show("Connection closed by server.")
End If
End Sub
End Class
```
在实际项目中,你可能需要将上述代码封装到类库中以便更好地管理和复用。运行服务器后,你可以从客户端实例化一个`TcpClient`并连接到它。
阅读全文