コード例 #1
0
        /// <summary>
        /// websocket监听
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private async Task ProcessRequest(AspNetWebSocketContext context)
        {
            var             socket    = context.WebSocket;
            string          uuid      = context.QueryString["uuid"].ToString();
            XzyWeChatThread xzy       = null;
            DicSocket       dicSocket = new DicSocket()
            {
                socket       = socket,
                weChatThread = xzy
            };

            if (_dicSockets.ContainsKey(uuid))
            {
                try
                {
                    await _dicSockets[uuid].socket.CloseAsync(WebSocketCloseStatus.Empty, string.Empty, CancellationToken.None);//如果client发起close请求,对client进行ack
                }
                catch (Exception ex)
                {
                    LogServer.Info(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "socketErr:" + ex.Message);
                }
            }
            _dicSockets.Add(uuid, dicSocket);
            while (true)
            {
                var buffer         = new ArraySegment <byte>(new byte[1024]);
                var receivedResult = await socket.ReceiveAsync(buffer, CancellationToken.None);//对web socket进行异步接收数据

                if (receivedResult.MessageType == WebSocketMessageType.Close)
                {
                    try
                    {
                        //从连接池移除对象,如果想保持websocket断线后 微信继续执行可以不做此操作
                        #region 微信注销线程释放
                        //string myuuid = _dicSockets.Where(p => p.Value.socket.Equals(socket)).FirstOrDefault().Key;
                        //_dicSockets[myuuid].weChatThread.Wx_Logout();
                        //_dicSockets[myuuid].weChatThread = null;
                        //_dicSockets.Remove(myuuid);
                        #endregion 微信注销线程释放

                        await socket.CloseAsync(WebSocketCloseStatus.Empty, string.Empty, CancellationToken.None);//如果client发起close请求,对client进行ack
                    }
                    catch (Exception ex)
                    {
                        LogServer.Info(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "socketErr:" + ex.Message);
                    }
                    break;
                }
                if (socket.State == System.Net.WebSockets.WebSocketState.Open)
                {
                    string      recvMsg = Encoding.UTF8.GetString(buffer.Array, 0, receivedResult.Count);
                    SocketModel model   = JsonConvert.DeserializeObject <SocketModel>(recvMsg);
                    switch (model.action.ToLower())
                    {
                    case "start":    //创建socket
                        await Task.Factory.StartNew(() =>
                        {
                            xzy = new XzyWeChatThread(socket);
                        });

                        break;

                    case "start62":    //通过账号密码+62数据登录
                        await Task.Factory.StartNew(() =>
                        {
                            SocketStart62 socketStart62 = JsonConvert.DeserializeObject <SocketStart62>(model.context);
                            xzy = new XzyWeChatThread(socket, socketStart62.username, socketStart62.password, socketStart62.str62);
                        });

                        break;
                    }
                }
            }
        }