[英]How to send messages from server to a specific client
I am using WebSockets and trying to set up a code base for my server-client. 我正在使用WebSockets,并尝试为我的服务器-客户端设置代码库。 I know how to send messages from client to server and I also know how to listen those messages from the server side.
我知道如何将消息从客户端发送到服务器,也知道如何从服务器端监听这些消息。
However, how can I send a message back to a client ? 但是,如何将消息发送回客户端?
// 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".
Basically you have to use the SendAsync
method: 基本上,您必须使用
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);
Take a look at this example: https://stackoverflow.com/a/26274839/307976 看一下这个例子: https : //stackoverflow.com/a/26274839/307976
您必须致电:
_clientsocket.Send(...);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.