一、服务端

  1. 创建HttpListener
1
private readonly HttpListener _listener = new HttpListener();
  1. 启动HttpListener监听
1
2
listener.Prefixes.Add(url);
listener.Start();
  1. 创建异步线程,监听客户端请求
1
2
3
4
5
6
7
8
9
10
11
12
Task.Run(async ()=> {
while (listener.IsListening){
//等待传入请求(作为异步操作)。
var context = await listener.GetContextAsync();
//有请求时,判断是否websocket请求
if (context.Request.IsWebSocketRequest){
await ProcessWebSocketRequest(context);
}else{
// Handle non-WebSocket requests
}
}
});
  1. 接收websocket连接,创建WebSocket对象
1
2
WebSocketContext webSocketContext = await context.AcceptWebSocketAsync(null);
WebSocket webSocket = webSocketContext.WebSocket;
  1. 判断websocket状态,接收处理消息
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
while (webSocket.State == WebSocketState.Open){
//1.定义缓冲区
ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024]);
//2.接收异步消息
WebSocketReceiveResult result = await webSocket.ReceiveAsync(buffer,CancellationToken.None);
//3.判断消息类型是否关闭
if (result.MessageType == WebSocketMessageType.Close){
//3.1关闭类型消息
await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
}else{
//3.2正常消息 message
string message = System.Text.Encoding.UTF8.GetString(buffer.Array, 0, result.Count);

//回传消息(可选)
ArraySegment buffer = new ArraySegment(Encoding.UTF8.GetBytes("server:"+message));
await webSocket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);
}
}