关于TCP通讯服务端与多个客户端进行连接
Public Class Form1Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'指定ip和端口
Dim ipAddress As = Nothing
(TextBox1.Text, ipAddress)
Dim localEndPoint As New (ipAddress, TextBox2.Text)
服务器端 = New (Net.Sockets.AddressFamily.InterNetwork, Net.Sockets.SocketType.Stream, Net.Sockets.ProtocolType.Tcp)
服务器端.Bind(localEndPoint)
服务器端.Listen(10)
监听线程 = New Threading.Thread(AddressOf 监听)
监听线程.Start()
End Sub
Public Sub 监听()
While True
连接(连接编号) = 服务器端.Accept()
TCP线程(连接编号) = New Threading.Thread(AddressOf 接收)
TCP线程(连接编号).Start()
End While
End Sub
Public Sub 接收()
Dim 编号 As Byte = 连接编号
'连接编号 = 连接编号 + 1
While True
Dim bytesRec As Integer = 连接(编号).Receive(bytes) '接收数据
If bytesRec > 0 Then
data = System.Text.Encoding.ASCII.GetString(bytes, 0, bytesRec)
End If
End While
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
If data <> Nothing Then
ListBox1.Items.Insert(0, data)
data = Nothing
End If
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
ListBox1.Items.Clear()
End Sub
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
On Error Resume Next
监听线程.Abort()
For i As Byte = 0 To 255
TCP线程(i).Abort()
连接(i).Shutdown(Net.Sockets.SocketShutdown.Both)
连接(i).Close()
Next
服务器端.Shutdown(Net.Sockets.SocketShutdown.Both)
服务器端.Close()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
On Error Resume Next
Dim msg As Byte() = System.Text.Encoding.ASCII.GetBytes(TextBox3.Text)
Dim bytesSent As Integer = 连接(连接编号).Send(msg) '发送数据
End Sub
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
On Error Resume Next
监听线程.Abort()
For i As Byte = 0 To 255
TCP线程(i).Abort()
连接(i).Shutdown(Net.Sockets.SocketShutdown.Both)
连接(i).Close()
Next
服务器端.Shutdown(Net.Sockets.SocketShutdown.Both)
服务器端.Close()
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
End Class