我正在使用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);
看一下这个例子:https://stackoverflow.com/a/26274839/307976
你必须调用:
_clientsocket.Send(...);