Exemple #1
0
    static int Close(IntPtr L)
    {
        try
        {
            int count = LuaDLL.lua_gettop(L);

            if (count == 1)
            {
                BestHTTP.WebSocket.WebSocketResponse obj = (BestHTTP.WebSocket.WebSocketResponse)ToLua.CheckObject(L, 1, typeof(BestHTTP.WebSocket.WebSocketResponse));
                obj.Close();
                return(0);
            }
            else if (count == 3)
            {
                BestHTTP.WebSocket.WebSocketResponse obj = (BestHTTP.WebSocket.WebSocketResponse)ToLua.CheckObject(L, 1, typeof(BestHTTP.WebSocket.WebSocketResponse));
                ushort arg0 = (ushort)LuaDLL.luaL_checknumber(L, 2);
                string arg1 = ToLua.CheckString(L, 3);
                obj.Close(arg0, arg1);
                return(0);
            }
            else
            {
                return(LuaDLL.luaL_throw(L, "invalid arguments to method: BestHTTP.WebSocket.WebSocketResponse.Close"));
            }
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e));
        }
    }
Exemple #2
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));
     }
 }
Exemple #3
0
    static int Send(IntPtr L)
    {
        try
        {
            int count = LuaDLL.lua_gettop(L);

            if (count == 2 && TypeChecker.CheckTypes <string>(L, 2))
            {
                BestHTTP.WebSocket.WebSocketResponse obj = (BestHTTP.WebSocket.WebSocketResponse)ToLua.CheckObject(L, 1, typeof(BestHTTP.WebSocket.WebSocketResponse));
                string arg0 = ToLua.ToString(L, 2);
                obj.Send(arg0);
                return(0);
            }
            else if (count == 2 && TypeChecker.CheckTypes <byte[]>(L, 2))
            {
                BestHTTP.WebSocket.WebSocketResponse obj = (BestHTTP.WebSocket.WebSocketResponse)ToLua.CheckObject(L, 1, typeof(BestHTTP.WebSocket.WebSocketResponse));
                byte[] arg0 = ToLua.CheckByteBuffer(L, 2);
                obj.Send(arg0);
                return(0);
            }
            else if (count == 2 && TypeChecker.CheckTypes <BestHTTP.WebSocket.Frames.WebSocketFrame>(L, 2))
            {
                BestHTTP.WebSocket.WebSocketResponse     obj  = (BestHTTP.WebSocket.WebSocketResponse)ToLua.CheckObject(L, 1, typeof(BestHTTP.WebSocket.WebSocketResponse));
                BestHTTP.WebSocket.Frames.WebSocketFrame arg0 = (BestHTTP.WebSocket.Frames.WebSocketFrame)ToLua.ToObject(L, 2);
                obj.Send(arg0);
                return(0);
            }
            else if (count == 4)
            {
                BestHTTP.WebSocket.WebSocketResponse obj = (BestHTTP.WebSocket.WebSocketResponse)ToLua.CheckObject(L, 1, typeof(BestHTTP.WebSocket.WebSocketResponse));
                byte[] arg0 = ToLua.CheckByteBuffer(L, 2);
                ulong  arg1 = LuaDLL.tolua_checkuint64(L, 3);
                ulong  arg2 = LuaDLL.tolua_checkuint64(L, 4);
                obj.Send(arg0, arg1, arg2);
                return(0);
            }
            else
            {
                return(LuaDLL.luaL_throw(L, "invalid arguments to method: BestHTTP.WebSocket.WebSocketResponse.Send"));
            }
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e));
        }
    }
Exemple #4
0
    static int get_MaxFragmentSize(IntPtr L)
    {
        object o = null;

        try
        {
            o = ToLua.ToObject(L, 1);
            BestHTTP.WebSocket.WebSocketResponse obj = (BestHTTP.WebSocket.WebSocketResponse)o;
            ushort ret = obj.MaxFragmentSize;
            LuaDLL.lua_pushnumber(L, ret);
            return(1);
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e, o, "attempt to index MaxFragmentSize on a nil value"));
        }
    }
Exemple #5
0
    static int get_IsClosed(IntPtr L)
    {
        object o = null;

        try
        {
            o = ToLua.ToObject(L, 1);
            BestHTTP.WebSocket.WebSocketResponse obj = (BestHTTP.WebSocket.WebSocketResponse)o;
            bool ret = obj.IsClosed;
            LuaDLL.lua_pushboolean(L, ret);
            return(1);
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e, o, "attempt to index IsClosed on a nil value"));
        }
    }
Exemple #6
0
    static int get_PingFrequnecy(IntPtr L)
    {
        object o = null;

        try
        {
            o = ToLua.ToObject(L, 1);
            BestHTTP.WebSocket.WebSocketResponse obj = (BestHTTP.WebSocket.WebSocketResponse)o;
            System.TimeSpan ret = obj.PingFrequnecy;
            ToLua.PushValue(L, ret);
            return(1);
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e, o, "attempt to index PingFrequnecy on a nil value"));
        }
    }
Exemple #7
0
    static int get_WebSocket(IntPtr L)
    {
        object o = null;

        try
        {
            o = ToLua.ToObject(L, 1);
            BestHTTP.WebSocket.WebSocketResponse obj = (BestHTTP.WebSocket.WebSocketResponse)o;
            BestHTTP.WebSocket.WebSocket         ret = obj.WebSocket;
            ToLua.PushSealed(L, ret);
            return(1);
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e, o, "attempt to index WebSocket on a nil value"));
        }
    }
Exemple #8
0
    static int get_ConnectionKey(IntPtr L)
    {
        object o = null;

        try
        {
            o = ToLua.ToObject(L, 1);
            BestHTTP.WebSocket.WebSocketResponse obj = (BestHTTP.WebSocket.WebSocketResponse)o;
            BestHTTP.Core.HostConnectionKey      ret = obj.ConnectionKey;
            ToLua.PushValue(L, ret);
            return(1);
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e, o, "attempt to index ConnectionKey on a nil value"));
        }
    }
Exemple #9
0
    static int get_lastMessage(IntPtr L)
    {
        object o = null;

        try
        {
            o = ToLua.ToObject(L, 1);
            BestHTTP.WebSocket.WebSocketResponse obj = (BestHTTP.WebSocket.WebSocketResponse)o;
            System.DateTime ret = obj.lastMessage;
            ToLua.PushValue(L, ret);
            return(1);
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e, o, "attempt to index lastMessage on a nil value"));
        }
    }
Exemple #10
0
    static int get_OnClosed(IntPtr L)
    {
        object o = null;

        try
        {
            o = ToLua.ToObject(L, 1);
            BestHTTP.WebSocket.WebSocketResponse obj = (BestHTTP.WebSocket.WebSocketResponse)o;
            System.Action <BestHTTP.WebSocket.WebSocketResponse, ushort, string> ret = obj.OnClosed;
            ToLua.Push(L, ret);
            return(1);
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e, o, "attempt to index OnClosed on a nil value"));
        }
    }
Exemple #11
0
    static int get_OnIncompleteFrame(IntPtr L)
    {
        object o = null;

        try
        {
            o = ToLua.ToObject(L, 1);
            BestHTTP.WebSocket.WebSocketResponse obj = (BestHTTP.WebSocket.WebSocketResponse)o;
            System.Action <BestHTTP.WebSocket.WebSocketResponse, BestHTTP.WebSocket.Frames.WebSocketFrameReader> ret = obj.OnIncompleteFrame;
            ToLua.Push(L, ret);
            return(1);
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e, o, "attempt to index OnIncompleteFrame on a nil value"));
        }
    }
Exemple #12
0
    static int set_OnClosed(IntPtr L)
    {
        object o = null;

        try
        {
            o = ToLua.ToObject(L, 1);
            BestHTTP.WebSocket.WebSocketResponse obj = (BestHTTP.WebSocket.WebSocketResponse)o;
            System.Action <BestHTTP.WebSocket.WebSocketResponse, ushort, string> arg0 = (System.Action <BestHTTP.WebSocket.WebSocketResponse, ushort, string>)ToLua.CheckDelegate <System.Action <BestHTTP.WebSocket.WebSocketResponse, ushort, string> >(L, 2);
            obj.OnClosed = arg0;
            return(0);
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e, o, "attempt to index OnClosed on a nil value"));
        }
    }
Exemple #13
0
    static int get_Latency(IntPtr L)
    {
        object o = null;

        try
        {
            o = ToLua.ToObject(L, 1);
            BestHTTP.WebSocket.WebSocketResponse obj = (BestHTTP.WebSocket.WebSocketResponse)o;
            int ret = obj.Latency;
            LuaDLL.lua_pushinteger(L, ret);
            return(1);
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e, o, "attempt to index Latency on a nil value"));
        }
    }
Exemple #14
0
    static int set_OnIncompleteFrame(IntPtr L)
    {
        object o = null;

        try
        {
            o = ToLua.ToObject(L, 1);
            BestHTTP.WebSocket.WebSocketResponse obj = (BestHTTP.WebSocket.WebSocketResponse)o;
            System.Action <BestHTTP.WebSocket.WebSocketResponse, BestHTTP.WebSocket.Frames.WebSocketFrameReader> arg0 = (System.Action <BestHTTP.WebSocket.WebSocketResponse, BestHTTP.WebSocket.Frames.WebSocketFrameReader>)ToLua.CheckDelegate <System.Action <BestHTTP.WebSocket.WebSocketResponse, BestHTTP.WebSocket.Frames.WebSocketFrameReader> >(L, 2);
            obj.OnIncompleteFrame = arg0;
            return(0);
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e, o, "attempt to index OnIncompleteFrame on a nil value"));
        }
    }
Exemple #15
0
    static int set_lastMessage(IntPtr L)
    {
        object o = null;

        try
        {
            o = ToLua.ToObject(L, 1);
            BestHTTP.WebSocket.WebSocketResponse obj = (BestHTTP.WebSocket.WebSocketResponse)o;
            System.DateTime arg0 = StackTraits <System.DateTime> .Check(L, 2);

            obj.lastMessage = arg0;
            return(0);
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e, o, "attempt to index lastMessage on a nil value"));
        }
    }
Exemple #16
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();
        }
Exemple #18
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();
        }
Exemple #20
0
 public WebSocket(Uri uri, string origin, string protocol = "")
 {
     this.PingFrequency = 1000;
     if (uri.Port == -1)
     {
         uri = new Uri(string.Concat(new string[]
         {
             uri.Scheme,
             "://",
             uri.Host,
             ":",
             (!uri.Scheme.Equals("wss", StringComparison.OrdinalIgnoreCase)) ? "80" : "443",
             uri.PathAndQuery
         }));
     }
     this.InternalRequest = new HTTPRequest(uri, delegate(HTTPRequest req, HTTPResponse resp)
     {
         if (((resp == null || req.Exception != null) && this.OnError != null) || (resp != null && resp.StatusCode != 101))
         {
             this.OnError(this, req.Exception);
         }
     });
     this.InternalRequest.SetHeader("Host", uri.Host + ":" + uri.Port);
     this.InternalRequest.SetHeader("Upgrade", "websocket");
     this.InternalRequest.SetHeader("Connection", "keep-alive, Upgrade");
     this.InternalRequest.SetHeader("Sec-WebSocket-Key", this.GetSecKey(new object[]
     {
         this,
         this.InternalRequest,
         uri,
         new object()
     }));
     if (!string.IsNullOrEmpty(origin))
     {
         this.InternalRequest.SetHeader("Origin", origin);
     }
     this.InternalRequest.SetHeader("Sec-WebSocket-Version", "13");
     if (!string.IsNullOrEmpty(protocol))
     {
         this.InternalRequest.SetHeader("Sec-WebSocket-Protocol", protocol);
     }
     this.InternalRequest.SetHeader("Cache-Control", "no-cache");
     this.InternalRequest.SetHeader("Pragma", "no-cache");
     this.InternalRequest.DisableCache = true;
     this.InternalRequest.OnUpgraded   = delegate(HTTPRequest req, HTTPResponse resp)
     {
         this.webSocket = (resp as WebSocketResponse);
         if (this.webSocket == null)
         {
             if (this.OnError != null)
             {
                 this.OnError(this, req.Exception);
             }
             return;
         }
         if (this.OnOpen != null)
         {
             this.OnOpen(this);
         }
         this.webSocket.OnText = delegate(WebSocketResponse ws, string msg)
         {
             if (this.OnMessage != null)
             {
                 this.OnMessage(this, msg);
             }
         };
         this.webSocket.OnBinary = delegate(WebSocketResponse ws, byte[] bin)
         {
             if (this.OnBinary != null)
             {
                 this.OnBinary(this, bin);
             }
         };
         this.webSocket.OnClosed = delegate(WebSocketResponse ws, ushort code, string msg)
         {
             if (this.OnClosed != null)
             {
                 this.OnClosed(this, code, msg);
             }
         };
         if (this.OnIncompleteFrame != null)
         {
             this.webSocket.OnIncompleteFrame = delegate(WebSocketResponse ws, WebSocketFrameReader frame)
             {
                 if (this.OnIncompleteFrame != null)
                 {
                     this.OnIncompleteFrame(this, frame);
                 }
             };
         }
         if (this.StartPingThread)
         {
             this.webSocket.StartPinging(Math.Min(this.PingFrequency, 100));
         }
     };
 }
Exemple #21
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();
        }
Exemple #22
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));
                };
        }
Exemple #23
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();
        }
        /// <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));
                };
        }