.net mvc使用websocket服务器及客户端简易代码
.net MVC服务端
Func<AspNetWebSocketContext, Task> func = new Func<AspNetWebSocketContext, Task>(async (socketContext) => { WebSocket socket = socketContext.WebSocket; await socket.SendAsync(GetText("我是服务器,连接成功"), WebSocketMessageType.Text, true, CancellationToken.None); while (socket.State == WebSocketState.Open) { ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024]); WebSocketReceiveResult result = await socket.ReceiveAsync(buffer, CancellationToken.None); // 解析消息内容 string userMessage = Encoding.UTF8.GetString(buffer.Array, 0, result.Count); //是否关闭链接 if (result.MessageType == WebSocketMessageType.Close) { break; } } }); System.Web.HttpContext.Current.AcceptWebSocketRequest(func);
public static ArraySegment<byte> GetText(string text) { return new ArraySegment<byte>(Encoding.UTF8.GetBytes(text)); }
网页客户端
var url = "ws://localhost:55939"; var socket; function connect() { var webSocketUrl = url + "?UserName=qqqq" + new Date(); //注意:下面这行代码执行之后就已经调通到后台的MyWebSocket方法中了。 socket = new WebSocket(webSocketUrl) //链接打开的时候触发 socket.onopen = function () { console.log("链接已打开"); // 定时发送一个消息给服务器发送心跳包 服务器接收到心跳包以后马上就再回复一个消息给客户端 // 如果我发现十秒钟或者在间隔时间内 接受不到服务器回复的心跳消息 我就认为连接掉线 // 这时候就需要断线 connect(); } // 接受服务器发送过来的消息 socket.onmessage = function (evt) { console.log(evt.data); } // 异常的时候触发方法 socket.onerror = function (evt) { console.log(evt); } // 链接关闭的时候触发 socket.onclose = function () { console.log("连接关闭了"); } } function Send() { socket.send(document.getElementById("msg").value); }
C#客户端
ClientWebSocket socket = new ClientWebSocket(); IAsyncResult asyncResult = socket.ConnectAsync(new Uri("wss://xxxxxx"), CancellationToken.None); bool isSuccess = asyncResult.AsyncWaitHandle.WaitOne(Timeout.Infinite, true); if (isSuccess&& socket.State == WebSocketState.Open) { //连接成功 } while (socket.State == WebSocketState.Open) { ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024]); WebSocketReceiveResult result = await socket.ReceiveAsync(buffer, CancellationToken.None); string userMessage = Encoding.UTF8.GetString(buffer.Array, 0, result.Count); }