Esempio n. 1
0
 static int StartPinging(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 2);
         BestHTTP.WebSocket.WebSocketResponse obj = (BestHTTP.WebSocket.WebSocketResponse)ToLua.CheckObject(L, 1, typeof(BestHTTP.WebSocket.WebSocketResponse));
         int arg0 = (int)LuaDLL.luaL_checknumber(L, 2);
         obj.StartPinging(arg0);
         return(0);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
Esempio n. 2
0
        private void OnInternalRequestUpgraded(HTTPRequest req, HTTPResponse resp)
        {
            webSocket = resp as WebSocketResponse;

            if (webSocket == null)
            {
                if (OnError != null)
                {
                    OnError(this, req.Exception);
                }

                if (OnErrorDesc != null)
                {
                    string reason = string.Empty;
                    if (req.Exception != null)
                    {
                        reason = req.Exception.Message + " " + req.Exception.StackTrace;
                    }

                    OnErrorDesc(this, reason);
                }

                return;
            }

            webSocket.WebSocket = this;

            if (this.Extensions != null)
            {
                for (int i = 0; i < this.Extensions.Length; ++i)
                {
                    var ext = this.Extensions[i];

                    try
                    {
                        if (ext != null && !ext.ParseNegotiation(webSocket))
                        {
                            this.Extensions[i] = null; // Keep extensions only that succesfully negotiated
                        }
                    }
                    catch (Exception ex)
                    {
                        HTTPManager.Logger.Exception("WebSocket", "ParseNegotiation", ex);

                        // Do not try to use a defective extension in the future
                        this.Extensions[i] = null;
                    }
                }
            }

            if (OnOpen != null)
            {
                try
                {
                    OnOpen(this);
                }
                catch (Exception ex)
                {
                    HTTPManager.Logger.Exception("WebSocket", "OnOpen", ex);
                }
            }

            webSocket.OnText = (ws, msg) =>
            {
                if (OnMessage != null)
                {
                    OnMessage(this, msg);
                }
            };

            webSocket.OnBinary = (ws, bin) =>
            {
                if (OnBinary != null)
                {
                    OnBinary(this, bin);
                }
            };

            webSocket.OnClosed = (ws, code, msg) =>
            {
                if (OnClosed != null)
                {
                    OnClosed(this, code, msg);
                }
            };

            if (OnIncompleteFrame != null)
            {
                webSocket.OnIncompleteFrame = (ws, frame) =>
                {
                    if (OnIncompleteFrame != null)
                    {
                        OnIncompleteFrame(this, frame);
                    }
                }
            }
            ;

            if (StartPingThread)
            {
                webSocket.StartPinging(Math.Max(PingFrequency, 100));
            }

            webSocket.StartReceive();
        }
Esempio n. 3
0
        /// <summary>
        /// Creates a WebSocket instance from the given uri, protocol and origin.
        /// </summary>
        /// <param name="uri">The uri of the WebSocket server</param>
        /// <param name="origin">Servers that are not intended to process input from any web page but only for certain sites SHOULD verify the |Origin| field is an origin they expect. 
        /// If the origin indicated is unacceptable to the server, then it SHOULD respond to the WebSocket handshake with a reply containing HTTP 403 Forbidden status code.</param>
        /// <param name="protocol">The application-level protocol that the client want to use(eg. "chat", "leaderboard", etc.). Can be null or empty string if not used.</param>
        public WebSocket(Uri uri, string origin, string protocol = "")
        {
            // Set up some default values.
            this.PingFrequency = 1000;

            // If there no port set in the uri, we must set it now.
            if (uri.Port == -1)
                // Somehow if i use the UriBuilder its not the same as if the uri is constructed from a string...
                //uri = new UriBuilder(uri.Scheme, uri.Host, uri.Scheme.Equals("wss", StringComparison.OrdinalIgnoreCase) ? 443 : 80, uri.PathAndQuery).Uri;
                uri = new Uri(uri.Scheme + "://" + uri.Host + ":" + (uri.Scheme.Equals("wss", StringComparison.OrdinalIgnoreCase) ? "443" : "80") + uri.PathAndQuery);

            InternalRequest = new HTTPRequest(uri, (req, resp) => {
                    if ((resp == null || req.Exception != null) && OnError != null || (resp != null && resp.StatusCode != 101))
                        OnError(this, req.Exception);
                });

            //http://tools.ietf.org/html/rfc6455#section-4

            //The request MUST contain a |Host| header field whose value contains /host/ plus optionally ":" followed by /port/ (when not using the default port).
            InternalRequest.SetHeader("Host", uri.Host + ":" + uri.Port);

            // The request MUST contain an |Upgrade| header field whose value MUST include the "websocket" keyword.
            InternalRequest.SetHeader("Upgrade", "websocket");

            // The request MUST contain a |Connection| header field whose value MUST include the "Upgrade" token.
            InternalRequest.SetHeader("Connection", "keep-alive, Upgrade");

            // The request MUST include a header field with the name |Sec-WebSocket-Key|.  The value of this header field MUST be a nonce consisting of a
            // randomly selected 16-byte value that has been base64-encoded (see Section 4 of [RFC4648]).  The nonce MUST be selected randomly for each connection.
            InternalRequest.SetHeader("Sec-WebSocket-Key", GetSecKey(new object[] { this, InternalRequest, uri, new object() }));

            // The request MUST include a header field with the name |Origin| [RFC6454] if the request is coming from a browser client.
            // If the connection is from a non-browser client, the request MAY include this header field if the semantics of that client match the use-case described here for browser clients.
            // More on Origin Considerations: http://tools.ietf.org/html/rfc6455#section-10.2
            if (!string.IsNullOrEmpty(origin))
                InternalRequest.SetHeader("Origin", origin);

            // The request MUST include a header field with the name |Sec-WebSocket-Version|.  The value of this header field MUST be 13.
            InternalRequest.SetHeader("Sec-WebSocket-Version", "13");

            if (!string.IsNullOrEmpty(protocol))
                InternalRequest.SetHeader("Sec-WebSocket-Protocol", protocol);

            // Disable caching
            InternalRequest.SetHeader("Cache-Control", "no-cache");
            InternalRequest.SetHeader("Pragma", "no-cache");

            InternalRequest.DisableCache = true;

            InternalRequest.OnUpgraded = (req, resp) =>
                {
                    webSocket = resp as WebSocketResponse;

                    if (webSocket == null)
                    {
                        if (OnError != null)
                            OnError(this, req.Exception);

                        return;
                    }

                    if (OnOpen != null)
                        OnOpen(this);

                    webSocket.OnText = (ws, msg) => {
                        if (OnMessage != null)
                            OnMessage(this, msg);
                    };

                    webSocket.OnBinary = (ws, bin) => {
                        if (OnBinary != null)
                            OnBinary(this, bin);
                    };

                    webSocket.OnClosed = (ws, code, msg) => {
                        if (OnClosed != null)
                            OnClosed(this, code, msg);
                    };

                    if (OnIncompleteFrame != null)
                        webSocket.OnIncompleteFrame = (ws, frame) => {
                            if (OnIncompleteFrame != null)
                                OnIncompleteFrame(this, frame);
                        };

                    if (StartPingThread)
                        webSocket.StartPinging(Math.Min(PingFrequency, 100));
                };
        }
Esempio n. 4
0
 public WebSocket(Uri uri, string origin, string protocol = "")
 {
     PingFrequency = 1000;
     if (uri.Port == -1)
     {
         uri = new Uri(uri.Scheme + "://" + uri.Host + ":" + ((!uri.Scheme.Equals("wss", StringComparison.OrdinalIgnoreCase)) ? "80" : "443") + uri.PathAndQuery);
     }
     InternalRequest = new HTTPRequest(uri, delegate(HTTPRequest req, HTTPResponse resp)
     {
         if ((resp == null || req.Exception != null) && OnError != null)
         {
             OnError(this, req.Exception);
         }
     });
     InternalRequest.SetHeader("Host", uri.Host + ":" + uri.Port);
     InternalRequest.SetHeader("Upgrade", "websocket");
     InternalRequest.SetHeader("Connection", "keep-alive, Upgrade");
     InternalRequest.SetHeader("Sec-WebSocket-Key", GetSecKey(new object[4]
     {
         this,
         InternalRequest,
         uri,
         new object()
     }));
     if (!string.IsNullOrEmpty(origin))
     {
         InternalRequest.SetHeader("Origin", origin);
     }
     InternalRequest.SetHeader("Sec-WebSocket-Version", "13");
     if (!string.IsNullOrEmpty(protocol))
     {
         InternalRequest.SetHeader("Sec-WebSocket-Protocol", protocol);
     }
     InternalRequest.SetHeader("Cache-Control", "no-cache");
     InternalRequest.SetHeader("Pragma", "no-cache");
     InternalRequest.OnUpgraded = delegate(HTTPRequest req, HTTPResponse resp)
     {
         webSocket = (resp as WebSocketResponse);
         if (webSocket == null)
         {
             if (OnError != null)
             {
                 OnError(this, req.Exception);
             }
         }
         else
         {
             if (OnOpen != null)
             {
                 OnOpen(this);
             }
             webSocket.OnText = delegate(WebSocketResponse ws, string msg)
             {
                 if (OnMessage != null)
                 {
                     OnMessage(this, msg);
                 }
             };
             webSocket.OnBinary = delegate(WebSocketResponse ws, byte[] bin)
             {
                 if (OnBinary != null)
                 {
                     OnBinary(this, bin);
                 }
             };
             webSocket.OnClosed = delegate(WebSocketResponse ws, ushort code, string msg)
             {
                 if (OnClosed != null)
                 {
                     OnClosed(this, code, msg);
                 }
             };
             if (OnPong != null)
             {
                 webSocket.OnPong = delegate(WebSocketResponse ws, byte[] bin)
                 {
                     if (OnPong != null)
                     {
                         OnPong(this, bin);
                     }
                 };
             }
             if (OnIncompleteFrame != null)
             {
                 webSocket.OnIncompleteFrame = delegate(WebSocketResponse ws, WebSocketFrameReader frame)
                 {
                     if (OnIncompleteFrame != null)
                     {
                         OnIncompleteFrame(this, frame);
                     }
                 };
             }
             if (StartPingThread)
             {
                 webSocket.StartPinging(Math.Max(PingFrequency, 100));
             }
         }
     };
 }
        private void OnInternalRequestUpgraded(HTTPRequest req, HTTPResponse resp)
        {
            HTTPManager.Logger.Information("WebSocket", "Internal request upgraded!", this.Context);
            webSocket = resp as WebSocketResponse;

            if (webSocket == null)
            {
                if (OnError != null)
                {
                    string reason = string.Empty;
                    if (req.Exception != null)
                    {
                        reason = req.Exception.Message + " " + req.Exception.StackTrace;
                    }

                    OnError(this, reason);
                }

                this.State = WebSocketStates.Closed;
                return;
            }

            // If Close called while we connected
            if (this.State == WebSocketStates.Closed)
            {
                webSocket.CloseStream();
                return;
            }

            if (!resp.HasHeader("sec-websocket-accept"))
            {
                this.State = WebSocketStates.Closed;
                webSocket.CloseStream();

                if (OnError != null)
                {
                    OnError(this, "No Sec-Websocket-Accept header is sent by the server!");
                }
                return;
            }

            webSocket.WebSocket = this;

            if (this.Extensions != null)
            {
                for (int i = 0; i < this.Extensions.Length; ++i)
                {
                    var ext = this.Extensions[i];

                    try
                    {
                        if (ext != null && !ext.ParseNegotiation(webSocket))
                        {
                            this.Extensions[i] = null; // Keep extensions only that successfully negotiated
                        }
                    }
                    catch (Exception ex)
                    {
                        HTTPManager.Logger.Exception("WebSocket", "ParseNegotiation", ex, this.Context);

                        // Do not try to use a defective extension in the future
                        this.Extensions[i] = null;
                    }
                }
            }

            this.State = WebSocketStates.Open;
            if (OnOpen != null)
            {
                try
                {
                    OnOpen(this);
                }
                catch (Exception ex)
                {
                    HTTPManager.Logger.Exception("WebSocket", "OnOpen", ex, this.Context);
                }
            }

            webSocket.OnText = (ws, msg) =>
            {
                if (OnMessage != null)
                {
                    OnMessage(this, msg);
                }
            };

            webSocket.OnBinary = (ws, bin) =>
            {
                if (OnBinary != null)
                {
                    OnBinary(this, bin);
                }
            };

            webSocket.OnClosed = (ws, code, msg) =>
            {
                this.State = WebSocketStates.Closed;

                if (OnClosed != null)
                {
                    OnClosed(this, code, msg);
                }
            };

            if (OnIncompleteFrame != null)
            {
                webSocket.OnIncompleteFrame = (ws, frame) =>
                {
                    if (OnIncompleteFrame != null)
                    {
                        OnIncompleteFrame(this, frame);
                    }
                }
            }
            ;

            if (StartPingThread)
            {
                webSocket.StartPinging(Math.Max(PingFrequency, 100));
            }

            webSocket.StartReceive();
        }
Esempio n. 6
0
        private void OnInternalRequestUpgraded(HTTPRequest req, HTTPResponse resp)
        {
            webSocket = resp as WebSocketResponse;

            if (webSocket == null)
            {
                if (OnError != null)
                {
                    OnError(this, req.Exception);
                }

                if (OnErrorDesc != null)
                {
                    string reason = string.Empty;
                    if (req.Exception != null)
                    {
                        reason = req.Exception.Message + " " + req.Exception.StackTrace;
                    }

                    OnErrorDesc(this, reason);
                }

                return;
            }

            if (OnOpen != null)
            {
                try
                {
                    OnOpen(this);
                }
                catch (Exception ex)
                {
                    HTTPManager.Logger.Exception("WebSocket", "OnOpen", ex);
                }
            }

            webSocket.OnText = (ws, msg) =>
            {
                if (OnMessage != null)
                {
                    OnMessage(this, msg);
                }
            };

            webSocket.OnBinary = (ws, bin) =>
            {
                if (OnBinary != null)
                {
                    OnBinary(this, bin);
                }
            };

            webSocket.OnClosed = (ws, code, msg) =>
            {
                if (OnClosed != null)
                {
                    OnClosed(this, code, msg);
                }
            };

            if (OnIncompleteFrame != null)
            {
                webSocket.OnIncompleteFrame = (ws, frame) =>
                {
                    if (OnIncompleteFrame != null)
                    {
                        OnIncompleteFrame(this, frame);
                    }
                }
            }
            ;

            if (StartPingThread)
            {
                webSocket.StartPinging(Math.Max(PingFrequency, 100));
            }

            webSocket.StartReceive();
        }
        private void OnInternalRequestUpgraded(HTTPRequest req, HTTPResponse resp)
        {
            webSocket = resp as WebSocketResponse;

            if (webSocket == null)
            {
                if (OnError != null)
                    OnError(this, req.Exception);

                if (OnErrorDesc != null)
                {
                    string reason = string.Empty;
                    if (req.Exception != null)
                        reason = req.Exception.Message + " " + req.Exception.StackTrace;

                    OnErrorDesc(this, reason);
                }

                return;
            }

            webSocket.WebSocket = this;

            if (this.Extensions != null)
            {
                for (int i = 0; i < this.Extensions.Length; ++i)
                {
                    var ext = this.Extensions[i];

                    try
                    {
                        if (ext != null && !ext.ParseNegotiation(webSocket))
                            this.Extensions[i] = null; // Keep extensions only that succesfully negotiated
                    }
                    catch (Exception ex)
                    {
                        HTTPManager.Logger.Exception("WebSocket", "ParseNegotiation", ex);

                        // Do not try to use a defective extension in the future
                        this.Extensions[i] = null;
                    }
                }
            }

            if (OnOpen != null)
            {
                try
                {
                    OnOpen(this);
                }
                catch(Exception ex)
                {
                    HTTPManager.Logger.Exception("WebSocket", "OnOpen", ex);
                }
            }

            webSocket.OnText = (ws, msg) =>
            {
                if (OnMessage != null)
                    OnMessage(this, msg);
            };

            webSocket.OnBinary = (ws, bin) =>
            {
                if (OnBinary != null)
                    OnBinary(this, bin);
            };

            webSocket.OnClosed = (ws, code, msg) =>
            {
                if (OnClosed != null)
                    OnClosed(this, code, msg);
            };

            if (OnIncompleteFrame != null)
                webSocket.OnIncompleteFrame = (ws, frame) =>
                {
                    if (OnIncompleteFrame != null)
                        OnIncompleteFrame(this, frame);
                };

            if (StartPingThread)
                webSocket.StartPinging(Math.Max(PingFrequency, 100));

            webSocket.StartReceive();
        }
Esempio n. 8
0
        private void OnInternalRequestUpgraded(HTTPRequest req, HTTPResponse resp)
        {
            webSocket = resp as WebSocketResponse;

            if (webSocket == null)
            {
                if (OnError != null)
                    OnError(this, req.Exception);

                if (OnErrorDesc != null)
                {
                    string reason = string.Empty;
                    if (req.Exception != null)
                        reason = req.Exception.Message + " " + req.Exception.StackTrace;

                    OnErrorDesc(this, reason);
                }

                return;
            }

            if (OnOpen != null)
            {
                try
                {
                    OnOpen(this);
                }
                catch(Exception ex)
                {
                    HTTPManager.Logger.Exception("WebSocket", "OnOpen", ex);
                }
            }

            webSocket.OnText = (ws, msg) =>
            {
                if (OnMessage != null)
                    OnMessage(this, msg);
            };

            webSocket.OnBinary = (ws, bin) =>
            {
                if (OnBinary != null)
                    OnBinary(this, bin);
            };

            webSocket.OnClosed = (ws, code, msg) =>
            {
                if (OnClosed != null)
                    OnClosed(this, code, msg);
            };

            if (OnIncompleteFrame != null)
                webSocket.OnIncompleteFrame = (ws, frame) =>
                {
                    if (OnIncompleteFrame != null)
                        OnIncompleteFrame(this, frame);
                };

            if (StartPingThread)
                webSocket.StartPinging(Math.Min(PingFrequency, 100));

            webSocket.StartReceive();
        }
Esempio n. 9
0
        /// <summary>
        /// Creates a WebSocket instance from the given uri, protocol and origin.
        /// </summary>
        /// <param name="uri">The uri of the WebSocket server</param>
        /// <param name="origin">Servers that are not intended to process input from any web page but only for certain sites SHOULD verify the |Origin| field is an origin they expect. 
        /// If the origin indicated is unacceptable to the server, then it SHOULD respond to the WebSocket handshake with a reply containing HTTP 403 Forbidden status code.</param>
        /// <param name="protocol">The application-level protocol that the client want to use(eg. "chat", "leaderboard", etc.). Can be null or empty string if not used.</param>
        public WebSocket(Uri uri, string origin, string protocol = "")
        {
            // Set up some default values.
            this.PingFrequency = 1000;

            // If there no port set in the uri, we must set it now.
            if (uri.Port == -1)
                // Somehow if i use the UriBuilder its not the same as if the uri is constructed from a string...
                //uri = new UriBuilder(uri.Scheme, uri.Host, uri.Scheme.Equals("wss", StringComparison.OrdinalIgnoreCase) ? 443 : 80, uri.PathAndQuery).Uri;
                uri = new Uri(uri.Scheme + "://" + uri.Host + ":" + (uri.Scheme.Equals("wss", StringComparison.OrdinalIgnoreCase) ? "443" : "80") + uri.PathAndQuery);

            InternalRequest = new HTTPRequest(uri, (req, resp) => {
                    if ((resp == null || req.Exception != null) && OnError != null || (resp != null && resp.StatusCode != 101))
                        OnError(this, req.Exception);
                });

            //http://tools.ietf.org/html/rfc6455#section-4

            //The request MUST contain a |Host| header field whose value contains /host/ plus optionally ":" followed by /port/ (when not using the default port).
            InternalRequest.SetHeader("Host", uri.Host + ":" + uri.Port);

            // The request MUST contain an |Upgrade| header field whose value MUST include the "websocket" keyword.
            InternalRequest.SetHeader("Upgrade", "websocket");

            // The request MUST contain a |Connection| header field whose value MUST include the "Upgrade" token.
            InternalRequest.SetHeader("Connection", "keep-alive, Upgrade");

            // The request MUST include a header field with the name |Sec-WebSocket-Key|.  The value of this header field MUST be a nonce consisting of a
            // randomly selected 16-byte value that has been base64-encoded (see Section 4 of [RFC4648]).  The nonce MUST be selected randomly for each connection.
            InternalRequest.SetHeader("Sec-WebSocket-Key", GetSecKey(new object[] { this, InternalRequest, uri, new object() }));

            // The request MUST include a header field with the name |Origin| [RFC6454] if the request is coming from a browser client.
            // If the connection is from a non-browser client, the request MAY include this header field if the semantics of that client match the use-case described here for browser clients.
            // More on Origin Considerations: http://tools.ietf.org/html/rfc6455#section-10.2
            if (!string.IsNullOrEmpty(origin))
                InternalRequest.SetHeader("Origin", origin);

            // The request MUST include a header field with the name |Sec-WebSocket-Version|.  The value of this header field MUST be 13.
            InternalRequest.SetHeader("Sec-WebSocket-Version", "13");

            if (!string.IsNullOrEmpty(protocol))
                InternalRequest.SetHeader("Sec-WebSocket-Protocol", protocol);

            // Disable caching
            InternalRequest.SetHeader("Cache-Control", "no-cache");
            InternalRequest.SetHeader("Pragma", "no-cache");

            InternalRequest.OnUpgraded = (req, resp) =>
                {
                    webSocket = resp as WebSocketResponse;

                    if (webSocket == null)
                    {
                        if (OnError != null)
                            OnError(this, req.Exception);

                        return;
                    }

                    if (OnOpen != null)
                        OnOpen(this);

                    webSocket.OnText = (ws, msg) => {
                        if (OnMessage != null)
                            OnMessage(this, msg);
                    };

                    webSocket.OnBinary = (ws, bin) => {
                        if (OnBinary != null)
                            OnBinary(this, bin);
                    };

                    webSocket.OnClosed = (ws, code, msg) => {
                        if (OnClosed != null)
                            OnClosed(this, code, msg);
                    };

                    if (OnIncompleteFrame != null)
                        webSocket.OnIncompleteFrame = (ws, frame) => {
                            if (OnIncompleteFrame != null)
                                OnIncompleteFrame(this, frame);
                        };

                    if (StartPingThread)
                        webSocket.StartPinging(Math.Min(PingFrequency, 100));
                };
        }