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