Beispiel #1
0
        private bool WebSocketProcess(HttpServerWebSocketContext context)
        {
            var secKey = context.RequestHeader["Sec-WebSocket-Key"];

            if (string.IsNullOrEmpty(secKey))
            {
                //请求的版本不接受支持,最低版本:  7
                context.Response(HttpStatusCode.HttpVersionNotSupported);
                return(false);
            }

            //握手信息
            var acceptKey = WebSocketHandshake.HandshakeSecurityHash09(secKey);

            context.ResponseHeader.Add("Sec-WebSocket-Accept", acceptKey);

            //响应客户端连接
            context.Response(HttpStatusCode.SwitchingProtocols);

            //call event
            if (this.WebSocketConnectioned == null)
            {
                return(false);
            }

            this.WebSocketConnectioned(context);

            if (context.Allowed == false)
            {
                return(false);
            }

            //receive
            context.Receive();

            //add session
            lock (this.websockets)
            {
                this.websockets.Add(context.Id, context);
            }

            return(true);
        }
Beispiel #2
0
        /// <summary>
        /// 以指定主机初始化实例
        /// </summary>
        /// <param name="host"></param>
        /// <param name="port"></param>
        /// <param name="path"></param>
        /// <param name="pingInterval">自动ping间隔,若设备为0则不进行ping检查</param>
        public WebSocketClient(string host, int port, string path, int pingInterval)
        {
            this.host         = host;
            this.port         = port;
            this.path         = path;
            this.pingInterval = pingInterval;

            if (pingInterval < 0)
            {
                throw new ArgumentOutOfRangeException("pingInterval", "pingInterval must than or equal zero.");
            }

            //local
            this.encoding = Encoding.UTF8;

            //handshaking
            var secWebSocketKey = RandomHelper.LetterAndNumber(16);

            this.handshakeSecurityHash09 = WebSocketHandshake.HandshakeSecurityHash09(secWebSocketKey);

            //init request header
            this.requestHeader = new Dictionary <string, string>(5, StringComparer.OrdinalIgnoreCase);
            this.requestHeader.Add("Host", host);
            this.requestHeader.Add("Connection", "Upgrade");
            this.requestHeader.Add("Upgrade", "websocket");
            this.requestHeader.Add("Sec-WebSocket-Key", secWebSocketKey);
            this.requestHeader.Add("Sec-WebSocket-Version", "" + WebSocketClient.VERSION);
            //
            this.responseHeader = new Dictionary <string, string>(5);
            //
            if (pingInterval > 0)
            {
                var millseconds = pingInterval * 1000;
                this.timer = new System.Threading.Timer(this.TimerCallback, null, millseconds, millseconds);
            }
        }