今天的项目需要用到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;
}
}
}
}

c# 在 websocket 中访问 session的更多相关文章

  1. 如何在WebSocket类中访问Session

    我最近正在做一个基于websocket的webQQ,最后代码会开源带github上,所以过程中我就不贴所有的代码啦~就贴问题的关键. 我在WebSocket里发消息的时候需要用到session,因为在 ...

  2. 在一般处理文件中访问Session需要添加IRequiresSessionState(转载)

    原文:http://blog.csdn.net/cdsnaspnet/article/details/5695625s 通常我们经常,通过session判定用户是否登录.还有一些临时的.重要的数据也尝 ...

  3. 在一般处理文件中访问Session需要添加IRequiresSessionState

    在IHttpHandler 使用Session 通常我们经常,通过session判定用户是否登录.还有一些临时的.重要的数据也尝尝存放在Session中. 在页面我们很容易的得到Session的值,但 ...

  4. ASP.NET Global Application_Error事件中访问Session报错 解决

    报错信息:会话状态在此上下文中不可用 protected void Application_Error(object sender, EventArgs e) { //以此判断是否可用Session ...

  5. 会话状态在此上下文中不可用HttpModule中无法访问Session原因

    写了一个自定义HttpModule,但始终访问不了Session,代码如下: public class RouteModule : IHttpModule, System.Web.SessionSta ...

  6. 使用java中的session来记录访问次数

    <%@ page import="java.net.CookieHandler" %><%-- Created by IntelliJ IDEA. User: D ...

  7. Tomcat中的Session小结

    什么是Session 对Tomcat而言,Session是一块在服务器开辟的内存空间,其存储结构为ConcurrentHashMap: Session的目的 Http协议是一种无状态协议,即每次服务端 ...

  8. 在IHttpHandler中获取session

    因为业务要异步通过IHttpHandler获得数据,但还要根据当前登录人员的session过滤,因此要在在IHttpHandler中获取session 方法是HttpHandler容器中如果需要访问S ...

  9. rails中的session

    学rails toturial的时候,第八章一直觉得有点没吃透,后来看了两篇rails关于session和cookies源码分析的文章,cookie原理与实现(rails篇) 和session原理与实 ...

随机推荐

  1. IOC和AOP的个人理解

    IOC,依赖倒置的意思,所谓依赖,从程序的角度看,就是比如A要调用B的方法,那么A就依赖于B,反正A要用到B,则A依赖于B. 所谓倒置,你必须理解如果不倒置,会怎么着,因为A必须要有B,才可以调用B, ...

  2. restful知识点之三restframework认证-->权限-->频率

    认证.权限.频率是层层递进的关系 权限业务时认证+权限 频率业务时:认证+权限+频率 局部认证方式 from django.conf.urls import url,include from djan ...

  3. leetcode Ch2-Dynamic Programming I

    一. 1. Edit Distance class Solution { public: int minDistance(string t1,string t2) { int len1=t1.size ...

  4. 使用TFHpple解析html

    使用TFHpple解析html https://github.com/topfunky/hpple 前期准备工作 引入静态库文件 添加库文件的 header search paths(注意,必须选中 ...

  5. HTTP协议图--HTTP 工作过程

                  HTTP请求响应模型 HTTP通信机制是在一次完整的 HTTP 通信过程中,客户端与服务器之间将完成下列7个步骤: 建立 TCP 连接 在HTTP工作开始之前,客户端首先要 ...

  6. Chapter 1 Secondary Sorting:Introduction

    开始学习<数据算法:Hadoop/Spark大数据处理技巧>第1-5章,假期有空就摘抄下来,毕竟不是纸质的可以写写画画,感觉这样效果好点,当然复杂的东西仍然跳过.写博客越发成了做笔记的感觉 ...

  7. 怎么知道是哪个div被点击了

    怎么知道是哪个div被点击了 不在div中加onclick等事件调用函数 ,用事件监听函数,但是如果div中的div被点击了,addEventListener得到了两个监听事件,我想点击div里的di ...

  8. UVA 12230 Crossing Rivers

    嘟嘟嘟 虽然分类是期望dp,不过好像是最水的 因为在陆地上的时间和概率是固定的,所以只用考虑过河的期望时间. 对于一条河p, l, v,p好像没什么用……不管了,首先期望时间我觉得可以这么算:期望时间 ...

  9. 【idea】配置node

    参考: http://blog.csdn.net/stubbornaccepted/article/details/71374673 http://www.cnblogs.com/duhuo/p/42 ...

  10. CS20Chapter2

    constants操作 import tensorflow as tf a = tf.constant([2, 2], name='a') b = tf.constant([[0, 1], [2, 3 ...