谢谢别人我解决了这个问题,我为每个客户宣布新的clientocket并解决了。 我只是从头代码中删除了clientSocket变量,并在每个线程上重新声明它。正如我在标题中所说,服务器不会监听以前客户端的数据包。一世 只需要服务器来读取来自多个客户端的所有数据包。
这是我的代码,谢谢你的帮助
serverSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) Dim ipAddress As IPAddress = ipAddress.Parse("192.168.2.202") Dim IpEndPoint As IPEndPoint = New IPEndPoint(ipAddress, 15002) serverSocket.Bind(IpEndPoint) serverSocket.Listen(1500) serverSocket.BeginAccept(New AsyncCallback(AddressOf OnAccept), Nothing)
委托Sub _OnAccept(ByVal ar As IAsyncResult) Private Sub OnAccept(ByVal ar As IAsyncResult)
If InvokeRequired Then Invoke(New _OnAccept(AddressOf OnAccept), ar) Exit Sub End If clientSocket = serverSocket.EndAccept(ar) serverSocket.BeginAccept(New AsyncCallback(AddressOf OnAccept), Nothing) Try clientSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None, New AsyncCallback(AddressOf OnRecieve),
ClientSocket的) 赶上前例外
End Try AddClient(clientSocket) End Sub Delegate Sub _AddClient(ByVal client As Socket) 'delege used to invoke AddCLient() Private Sub AddClient(ByVal client As Socket) If InvokeRequired Then Invoke(New _AddClient(AddressOf AddClient), client) Exit Sub End If Dim lvi As New ListViewItem(client.LocalEndPoint.ToString) lvi.Tag = client ListBox1.Items.Add(client.RemoteEndPoint.ToString & " Bağlandı") End Sub
委托Sub _OnRecieve(ByVal ar As IAsyncResult) Private Sub OnRecieve(ByVal ar As IAsyncResult) 如果InvokeRequired那么 调用(新_OnRecieve(AddressOf OnRecieve),ar) 退出子 结束如果
Dim client As Socket = ar.AsyncState Try client.EndReceive(ar) Catch ex As Exception End Try Dim bytesRec As Byte() = byteData Dim paket As String = System.Text.ASCIIEncoding.ASCII.GetString(bytesRec) Dim temizip As String temizip = Replace(paket, Chr(0), Chr(32)) temizip = temizip.Trim Dim msg As String = temizip Try Dim boyut As Integer boyut = msg(0) & msg(1) boyut = boyut - 10 Dim externalip As String externalip = msg.Remove(0, 2) externalip = externalip.Remove(boyut, (externalip.Length - boyut)) If clientlist.Contains(externalip) Then Else clientlist.Add(externalip) End If Catch ex As Exception End Try Try clientSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None, New AsyncCallback(AddressOf OnRecieve),
ClientSocket的) 赶上前例外
End Try End Sub