コード例 #1
0
        public static void Connect()
        {
            dic_Sockets = new Dictionary <string, WebSocketViewModel>();
            WebSocketServer    server          = new WebSocketServer("ws://0.0.0.0:9527");//监听所有的的地址
            WebSocketViewModel socketViewModel = new WebSocketViewModel();

            //出错后进行重启
            server.RestartAfterListenError = true;
            server.Start(socket => {
                socket.OnOpen = () =>   //连接建立事件
                {
                    //获取客户端网页的url
                    string clientUrl       = socket.ConnectionInfo.ClientIpAddress + ":" + socket.ConnectionInfo.ClientPort;
                    socketViewModel.socket = socket;
                    socketViewModel.IP     = clientUrl;
                    dic_Sockets.Add(clientUrl, socketViewModel);
                    LogTool.Write("|服务器:和客户端网页:" + clientUrl + " 建立WebSock连接!" + "当前连接数量:" + dic_Sockets.Count);
                };
                socket.OnClose = () =>  //连接关闭事件
                {
                    string clientUrl = socket.ConnectionInfo.ClientIpAddress + ":" + socket.ConnectionInfo.ClientPort;
                    //如果存在这个客户端,那么对这个socket进行移除
                    if (dic_Sockets.ContainsKey(clientUrl))
                    {
                        //注:Fleck中有释放
                        //关闭对象连接
                        //if (dic_Sockets[clientUrl] != null)
                        //{
                        //dic_Sockets[clientUrl].Close();
                        //}
                        dic_Sockets.Remove(clientUrl);
                    }
                    LogTool.Write("|服务器:和客户端网页:" + clientUrl + " 断开WebSock连接!");
                };
                socket.OnMessage = message =>  //接受客户端网页消息事件
                {
                    string clientUrl  = socket.ConnectionInfo.ClientIpAddress + ":" + socket.ConnectionInfo.ClientPort;
                    JObject ResponObj = JsonConvert.DeserializeObject <JObject>(message);
                    if (ResponObj != null)
                    {
                        if (ResponObj["msgId"] != null)  //把设备发送的数据缓存起来,时长30秒
                        {
                            WebApiApplication.SetCache(ResponObj["msgId"].ToString(), ResponObj, 30);
                        }
                        if (ResponObj["url"] != null)
                        {
                            if (ResponObj["url"].ToString() == "login")
                            {
                                socketViewModel.deviceSerial = ResponObj["deviceSerial"].ToString();
                                var obj = new { msgId = ResponObj["msgId"].ToString(), errCode = 0, errMsg = "success" };
                                socket.Send(JsonConvert.SerializeObject(obj));
                            }
                        }
                    }
                    LogTool.WriteData("|服务器:【收到】来客户端:" + clientUrl + "的信息:\n" + message);
                };
            });
        }