套接字多连接VB.NET

时间:2013-09-23 22:28:19

标签: vb.net sockets connection client

我希望向多台计算机(LAN网络)发送消息。

实验室中的每台计算机都在运行服务器,但客户端只有一台计算机。

问题:一旦将消息发送到第一台计算机,客户端就会停止发送到其他计算机。

客户:

Dim ip As String
Dim i As Integer
Dim serverStream As NetworkStream
Dim outStream As Byte()

Dim counter As Integer = 0
For i = 0 To 100

Try
ip = txtRange.Text & i

clientSocket.Connect(ip, 8888)

If clientSocket.Connected = True Then

serverStream = clientSocket.GetStream()
outStream = System.Text.Encoding.ASCII.GetBytes("Message from the client$")
serverStream.Write(outStream, 0, outStream.Length)
serverStream.Flush()

End If

Catch ex As Exception
End Try
Next

服务器:

Dim serverSocket As New TcpListener(8888)
Dim requestCount As Integer
Dim clientSocket As TcpClient
serverSocket.Start()
clientSocket = serverSocket.AcceptTcpClient()

While (true)

Dim networkStream As NetworkStream = clientSocket.GetStream()
Dim bytesFrom(10024) As Byte
networkStream.Read(bytesFrom, 0, CInt(clientSocket.ReceiveBufferSize))
Dim dataFromClient As String = System.Text.Encoding.ASCII.GetString(bytesFrom)
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"))
MessageBox.Show("Data from client -  " + dataFromClient)
End While


clientSocket.Close()
serverSocket.Stop()
谢谢。

1 个答案:

答案 0 :(得分:1)

客户端连接但从不断开连接。因此,第二次尝试连接套接字时已经连接并因此抛出异常。这个例外被捕获但被忽略了。

所以你应该改变两件事:

  1. 至少将Exception写入System.Diagnostics.Debug以在Visual Studio中运行时查看异常
  2. 使用后断开客户端套接字并在再次连接之前创建新套接字