c# 在 websocket 中访问 session
今天的项目需要用到websocket,但是中websocket中无法直接访问session,一访问session就出错,断开连接。
找了老半天百度也没有相关c#的介绍和方法,没办法,找不到现成的代码,只能自己动手了,
websocket握手时是一个完整的http协议的,发现里面有发送cookie:ASP.NET_SessionId,好了,废话少说,上测试
新建一个WebApi控制器
1 public class WebApiTestController : ApiController 2 { 3 public HttpResponseMessage Get() 4 { 5 if (HttpContext.Current.IsWebSocketRequest) 6 { 7 var user = (SysUser.UserInfoClass)HttpContext.Current.Session["user"];//此外是用户session,调试发现获取成功14 } 15 return new HttpResponseMessage(HttpStatusCode.SwitchingProtocols); 16 }
17 }
客户端js代码
1 <script type="text/javascript"> 2 var ws = new WebSocket("ws://" + window.location.hostname + ":" + window.location.port + "/api/WebApiTest/"); 3 </script>
验证成功,下面完善整个代码:
客户端js:
1 <!DOCTYPE html> 2 3 <html> 4 <head> 5 <meta name="viewport" content="width=device-width" /> 6 <title>WebSocket</title> 7 <script type="text/javascript" src="~/scripts/jquery.js"></script> 8 </head> 9 <body> 10 <fieldset> 11 <input type="button" value="Connect" id="btnConnect" /> 12 <input type="button" value="DisConnect" id="btnDisConnect" /> 13 <hr /> 14 <input type="text" id="txtInput" /> 15 <input type="button" value="Send" id="btnSend" /> 16 <br /> 17 <span id="messageSpan" style="color:red;"></span> 18 </fieldset> 19 </body> 20 </html> 21 <script type="text/javascript"> 22 var ws; 23 $("#btnConnect").click(function () { 24 $("#messageSpan").text("Connection..."); 25 ws = new WebSocket("ws://" + window.location.hostname + ":" + window.location.port + "/api/WebApiTest/"); 26 ws.onopen = function () { 27 $("#messageSpan").text("Connected!"); 28 }; 29 ws.onmessage = function (result) { 30 $("#messageSpan").text(result.data); 31 }; 32 ws.onerror = function (error) { 33 $("#messageSpan").text(error.data); 34 }; 35 ws.onclose = function () { 36 $("#messageSpan").text("Disconnected!"); 37 }; 38 }); 39 $("#btnSend").click(function () { 40 ws.protocol 41 if (ws.readyState == WebSocket.OPEN) { 42 ws.send($("#txtInput").val()); 43 } 44 else { 45 $("messageSpan").text("Connection is Closed!"); 46 } 47 }); 48 $("#btnDisconnect").click(function () { 49 ws.close(); 50 }); 51 </script>
服务器端(mvc.net)
1 public class WebApiTestController : ApiController 2 { 3 public HttpResponseMessage Get() 4 { 5 if (HttpContext.Current.IsWebSocketRequest) 6 { 7 var user = (Api_System.JsonClass.SysUser.UserInfoClass)HttpContext.Current.Session["user"]; 8 var ooo = new Func<AspNetWebSocketContext, Task>((x) => ProcessWSChat(x, user)); 9 HttpContext.Current.AcceptWebSocketRequest(ooo); 10 } 11 return new HttpResponseMessage(HttpStatusCode.SwitchingProtocols); 12 } 13 14 private async Task ProcessWSChat(AspNetWebSocketContext arg, SysUser.UserInfoClass user) 15 { 16 WebSocket socket = arg.WebSocket; 17 while (true) 18 { 19 ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024]); 20 WebSocketReceiveResult result = await socket.ReceiveAsync(buffer, CancellationToken.None); 21 if (socket.State == WebSocketState.Open) 22 { 23 //客户端发送来的信息 24 string message = Encoding.UTF8.GetString(buffer.Array, 0, result.Count); 25 string returnMessage = " You send :" + message + ". and the user is [" + user.UserName + "] at " + DateTime.Now.ToLongTimeString(); 26 buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(returnMessage)); 27 await socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None); 28 } 29 else 30 { 31 break; 32 } 33 } 34 } 35 }