HTML5 WebSocket+Asp.Net 实例四-用户标识,后台推送

一、Asp.Net 后台操作定义

注:当前示例仅考虑了单个链接的打开,对于多页面打开或者换浏览器打开的情况没做处理。

/// 
/// Socket后台代码示例
/// 
public class SocketOneController : Controller
{
    static Dictionary CONNECT_POOL = new Dictionary();//用户连接池
    //测试1,定义socke监听
    public void One(string user)
    {
        HttpContextBase context = ControllerContext.HttpContext;
        context.AcceptWebSocketRequest(async (ctx) =>
        {
            //开启socket监听
            WebSocket socket = ctx.WebSocket;

            while (true)
            {
                ArraySegment buffer = new ArraySegment(new byte[1024]);
                CancellationToken token;
                if (socket.State == WebSocketState.Open)
                {
                    //后台上线处理
                    if (CONNECT_POOL.Keys.Contains(user) == false)
                        CONNECT_POOL.Add(user, socket);

                    WebSocketReceiveResult result = await socket.ReceiveAsync(buffer, token);
                    string userMessage = Encoding.UTF8.GetString(buffer.Array, 0, result.Count);

                    userMessage = "You sent: " + userMessage + " at " +
                    DateTime.Now.ToLongTimeString();

                    //响应处理
                    buffer = new ArraySegment(Encoding.UTF8.GetBytes(userMessage));
                    await socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);
                }
                else
                {
                    //离线处理
                    CONNECT_POOL.Remove(user);
                    break;
                }
            }
        });
    }
    //后台执行发送操作
    public string Handle(string user)
    {
        if (CONNECT_POOL.Keys.Contains(user) == false)
            return "当前连接已经断开";

        WebSocket socket = CONNECT_POOL[user];

        byte[] bytes = Encoding.UTF8.GetBytes($"后台发送通知 at {DateTime.Now.ToString()}");
        ArraySegment buffer = new ArraySegment(bytes);
        socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);

        return "操作成功";
    }
}

二、Html5 前台简单代码示例

var url = 'ws://localhost:61870/socketone/one?user=' + $('#userOne').val();
var ws = new WebSocket(url);
ws.onopen = function () {
    console.info('创建连接成功');
}
ws.onmessage = function (e) {
    var data = e.data;
    console.info(data);
}
ws.onerror = function (e) {
    console.error(e);
}
ws.onclose = function () {
    console.info('连接关闭');
}
//发送内容处理
$('#btnOne').click(function () {
    if (ws.readyState == WebSocket.OPEN) {
        ws.send("来此客户端测试内容");
    } else {
        console.error('连接已经关闭');
    }
});
//关闭连接
$('#btnTwo').click(function () {
    ws.close();
});

 

更多:

HTML5 WebSocket实例(三)-文件上传处理

HTML5 WebSocketAPI实例(二)

HTML5 WebSocket实例(一)

你可能感兴趣的:(Asp.net,SignalR)