我想使用VB.NET控制台通过使用TCP / IP的服务器在两个客户端之间发送消息。我使用了this YouTuber中的代码来创建一个非常基本的聊天客户端应用程序,该聊天客户端连接到服务器并发送消息,然后服务器将消息发送给发件人之外的每个已连接客户端。>
我想做的,但我不知道,是让服务器在第一次连接时记住客户端的ID,并将其存储在包含有关客户端的相关信息的列表或数组中;然后,每当客户端发送后续消息时,服务器都会检查该客户端的ID,并在数组中查找该ID,然后在执行操作之前正确识别该客户端。
这里是代码(在YouTube上归功于Carlo De Silva),我在>>之后添加了一个代码,我想它可以实现符合我想要的功能的代码。
Sub Main()
Try
'Create a new server using the local IP address (whatever it is)
_server = New TcpListener(IPAddress.Any, port)
_server.Start()
'Starts a new thread which listens for clients connecting.
Threading.ThreadPool.QueueUserWorkItem(AddressOf NewClient)
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Console.ReadLine()
End Sub
Private Sub NewClient(state As Object)
Dim client As TcpClient = _server.AcceptTcpClient
Try
Threading.ThreadPool.QueueUserWorkItem(AddressOf NewClient)
_listOfClients.Add(client)
'Creates a new network stream receiving data from the client.
Dim ns As NetworkStream = client.GetStream
'>> Dim clientid = IDENTIFY CLIENT AFTER IT HAS CONNECTED
While True
'Creates a buffer
Dim toReceive(100000) As Byte
Dim length As Integer = ns.Read(toReceive, 0, toReceive.Length)
Dim text As String = Encoding.ASCII.GetString(toReceive, 0, length)
'>> BASED ON CLIENT ID, TAKE ACTION. (e.g. change text colour, add client name etc.)
For Each c As TcpClient In _listOfClients
If c IsNot client Then 'Sends a message to every other client besides this one.
Dim nns As NetworkStream = c.GetStream 'New Network Stream
nns.Write(Encoding.ASCII.GetBytes(text), 0, text.Length)
End If
Next
Console.WriteLine(text)
Console.WriteLine()
'Sends a received message receipt.
Dim message As String = "Message Received ..."
Dim toSend() As Byte = Encoding.ASCII.GetBytes(message)
ns.Write(toSend, 0, toSend.Length)
End While
Catch ex As Exception
If _listOfClients.Contains(client) Then
_listOfClients.Remove(client)
End If
Console.WriteLine(ex.Message)
End Try
End Sub
我了解此代码背后的基本概念,即发送和接收消息,但是我不知道我应该使用哪种方法来识别客户端。有人可以帮忙吗?