如何将消息从服务器发送到特定客户端
How to send messages from server to a specific client
我正在使用 WebSockets 并尝试为我的服务器客户端设置代码库。我知道如何从客户端向服务器发送消息,我也知道如何从服务器端收听这些消息。
但是,如何将消息发回客户端?
// here is the _clientSocket that I accepted
_clientSocket = _serverSocket.Accept();
int received = _clientSocket.Receive(_buffer, 0, _buffer.Length,
SocketFlags.None);
// here is the message I got from the client
string receivedMsg = Encoding.ASCII.GetString(_buffer);
if (receivedMsg == "1")
//TO DO: send back to client "This is a test message from server".
基本上你必须使用SendAsync
方法:
var sendbuffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes("Whatever text you want to send"));
await socket.SendAsync(sendbuffer , WebSocketMessageType.Text, true, CancellationToken.None)
.ConfigureAwait(false);
看看这个例子:
您必须致电:
_clientsocket.Send(...);
我正在使用 WebSockets 并尝试为我的服务器客户端设置代码库。我知道如何从客户端向服务器发送消息,我也知道如何从服务器端收听这些消息。
但是,如何将消息发回客户端?
// here is the _clientSocket that I accepted
_clientSocket = _serverSocket.Accept();
int received = _clientSocket.Receive(_buffer, 0, _buffer.Length,
SocketFlags.None);
// here is the message I got from the client
string receivedMsg = Encoding.ASCII.GetString(_buffer);
if (receivedMsg == "1")
//TO DO: send back to client "This is a test message from server".
基本上你必须使用SendAsync
方法:
var sendbuffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes("Whatever text you want to send"));
await socket.SendAsync(sendbuffer , WebSocketMessageType.Text, true, CancellationToken.None)
.ConfigureAwait(false);
看看这个例子:
您必须致电:
_clientsocket.Send(...);