示例#1
0
 public override void Stop()
 {
     if (wSocket != null)
     {
         wSocket.OnOpen      = null;
         wSocket.OnMessage   = null;
         wSocket.OnClosed    = null;
         wSocket.OnErrorDesc = null;
         wSocket.Close();
         wSocket = null;
     }
 }
        // The websocket connection is open
        private void OnOpen(WebSocket.WebSocket webSocket)
        {
            HTTPManager.Logger.Verbose("WebSocketTransport", "OnOpen");

            // https://github.com/aspnet/SignalR/blob/dev/specs/HubProtocol.md#overview
            // When our websocket connection is open, send the 'negotiation' message to the server.

            string json = string.Format("{{'protocol':'{0}', 'version': 1}}", this.connection.Protocol.Encoder.Name);

            byte[] buffer = JsonProtocol.WithSeparator(json);

            (this as ITransport).Send(buffer);
        }
示例#3
0
        private void OnError(WebSocket.WebSocket webSocket, string reason)
        {
            HTTPManager.Logger.Verbose("WebSocketTransport", "OnError: " + reason);

            if (this.State == TransportStates.Closing)
            {
                this.State = TransportStates.Closed;
            }
            else
            {
                this.ErrorReason = reason;
                this.State       = TransportStates.Failed;
            }
        }
示例#4
0
        void WSocket_OnMessage(WebSocket.WebSocket webSocket, string message)
        {
            if (webSocket != wSocket)
            {
                return;
            }

            IServerMessage msg = TransportBase.Parse(Connection.JsonEncoder, message);

            if (msg != null)
            {
                Connection.OnMessage(msg);
            }
        }
示例#5
0
        /// <summary>
        /// Called when an error occured on client side
        /// </summary>
        void OnError(WebSocket.WebSocket ws, Exception ex)
        {
            string errorMsg = string.Empty;

#if !UNITY_WEBGL || UNITY_EDITOR
            if (ws.InternalRequest.Response != null)
            {
                errorMsg = string.Format("Status Code from Server: {0} and Message: {1}", ws.InternalRequest.Response.StatusCode, ws.InternalRequest.Response.Message);
            }
#endif

            Text += string.Format("-An error occured: {0}\n", (ex != null ? ex.Message : "Unknown Error " + errorMsg));

            webSocket = null;
        }
        void WSocket_OnMessage(WebSocket.WebSocket webSocket, string message)
        {
            if (webSocket != wSocket)
            {
                return;
            }

#if UNITY_EDITOR
            VKDebug.Log(message, VKCommon.HEX_GREEN);
#endif

            IServerMessage msg = TransportBase.Parse(Connection.JsonEncoder, message);

            if (msg != null)
            {
                Connection.OnMessage(msg);
            }
        }
示例#7
0
        protected void closeWebSocketClient()
        {
            if (this.wsClient != null)
            {
                // unwire events
                this.wsClient.Closed          -= this.wsClient_Closed;
                this.wsClient.MessageReceived -= wsClient_MessageReceived;
                this.wsClient.Error           -= wsClient_Error;
                this.wsClient.Opened          -= this.wsClient_OpenEvent;

                if (this.wsClient.State == WebSocketState.Connecting || this.wsClient.State == WebSocketState.Open)
                {
                    try { this.wsClient.Close(); }
                    catch { Debug.WriteLine("exception raised trying to close websocket: can safely ignore, socket is being closed"); }
                }
                this.wsClient = null;
            }
        }
        void ITransport.StartConnect()
        {
            HTTPManager.Logger.Verbose("WebSocketTransport", "StartConnect");

            if (this.webSocket == null)
            {
                Uri baseUri = this.connection.Uri;

                // If we received an Url in the negotiation result, we have to connect to that endpoint.
                if (this.connection.NegotiationResult != null && this.connection.NegotiationResult.Url != null)
                {
                    baseUri = this.connection.NegotiationResult.Url;
                }

                Uri uri = BuildUri(baseUri);

                // Also, if there's an authentication provider it can alter further our uri.
                if (this.connection.AuthenticationProvider != null)
                {
                    uri = this.connection.AuthenticationProvider.PrepareUri(uri) ?? uri;
                }

                HTTPManager.Logger.Verbose("WebSocketTransport", "StartConnect connecting to Uri: " + uri.ToString());

                this.webSocket = new WebSocket.WebSocket(uri);
            }

#if !UNITY_WEBGL || UNITY_EDITOR
            // prepare the internal http request
            if (this.connection.AuthenticationProvider != null)
            {
                this.connection.AuthenticationProvider.PrepareRequest(webSocket.InternalRequest);
            }
#endif
            this.webSocket.OnOpen      += OnOpen;
            this.webSocket.OnMessage   += OnMessage;
            this.webSocket.OnBinary    += OnBinary;
            this.webSocket.OnErrorDesc += OnError;
            this.webSocket.OnClosed    += OnClosed;

            this.webSocket.Open();

            this.State = TransportStates.Connecting;
        }
        private void OnMessage(WebSocket.WebSocket webSocket, string data)
        {
            if (this.State == TransportStates.Closing)
            {
                return;
            }

            if (this.State == TransportStates.Connecting)
            {
                HandleHandshakeResponse(data);

                return;
            }

            this.messages.Clear();
            try
            {
                int len = System.Text.Encoding.UTF8.GetByteCount(data);

                byte[] buffer = BufferPool.Get(len, true);
                try
                {
                    Array.Clear(buffer, 0, buffer.Length);

                    System.Text.Encoding.UTF8.GetBytes(data, 0, data.Length, buffer, 0);

                    this.connection.Protocol.ParseMessages(new BufferSegment(buffer, 0, len), ref this.messages);
                }
                finally
                {
                    BufferPool.Release(buffer);
                }

                this.connection.OnMessages(this.messages);
            }
            catch (Exception ex)
            {
                HTTPManager.Logger.Exception("WebSocketTransport", "OnMessage(string)", ex, this.Context);
            }
            finally
            {
                this.messages.Clear();
            }
        }
        public override void StartConnect()
        {
            HTTPManager.Logger.Verbose("WebSocketTransport", "StartConnect", this.Context);

            if (this.webSocket == null)
            {
                Uri    uri    = this.connection.Uri;
                string scheme = Connections.HTTPProtocolFactory.IsSecureProtocol(uri) ? "wss" : "ws";
                int    port   = uri.Port != -1 ? uri.Port : (scheme.Equals("wss", StringComparison.OrdinalIgnoreCase) ? 443 : 80);

                // Somehow if i use the UriBuilder it's not the same as if the uri is constructed from a string...
                uri = new Uri(scheme + "://" + uri.Host + ":" + port + uri.GetRequestPathAndQueryURL());

                uri = BuildUri(uri);

                // Also, if there's an authentication provider it can alter further our uri.
                if (this.connection.AuthenticationProvider != null)
                {
                    uri = this.connection.AuthenticationProvider.PrepareUri(uri) ?? uri;
                }

                HTTPManager.Logger.Verbose("WebSocketTransport", "StartConnect connecting to Uri: " + uri.ToString(), this.Context);

                this.webSocket = new WebSocket.WebSocket(uri);
                this.webSocket.Context.Add("Transport", this.Context);
            }

#if !UNITY_WEBGL || UNITY_EDITOR
            // prepare the internal http request
            if (this.connection.AuthenticationProvider != null)
            {
                webSocket.OnInternalRequestCreated = (ws, internalRequest) => this.connection.AuthenticationProvider.PrepareRequest(internalRequest);
            }
#endif
            this.webSocket.OnOpen    += OnOpen;
            this.webSocket.OnMessage += OnMessage;
            this.webSocket.OnBinary  += OnBinary;
            this.webSocket.OnError   += OnError;
            this.webSocket.OnClosed  += OnClosed;

            this.webSocket.Open();

            this.State = TransportStates.Connecting;
        }
示例#11
0
        /// <summary>
        /// Initiate the connection with Socket.IO service
        /// </summary>
        public void Connect()
        {
            lock (padLock)
            {
                if (!(this.ReadyState == WebSocketState.Connecting || this.ReadyState == WebSocketState.Open))
                {
                    try
                    {
                        this.ConnectionOpenEvent.Reset();
                        this.requestHandshake(uri);                        // perform an initial HTTP request as a new, non-handshaken connection

                        if (string.IsNullOrWhiteSpace(this.HandShake.SID) || this.HandShake.HadError)
                        {
                            this.LastErrorMessage = string.Format("Error initializing handshake with {0}", uri.ToString());
                            this.OnErrorEvent(this, new ErrorEventArgs(this.LastErrorMessage, new Exception()));
                        }
                        else
                        {
                            string wsScheme = (uri.Scheme == Uri.UriSchemeHttps ? "wss" : "ws");
                            string host     = uri.Host.Contains("localhost") || uri.Host.Contains("127.0.0.1") ? IPAddress.Loopback.ToString() : uri.Host;
                            this.wsClient = new WebSocket.WebSocket(
                                string.Format("{0}://{1}:{2}/socket.io/1/websocket/{3}", wsScheme, host, uri.Port, this.HandShake.SID),
                                string.Empty,
                                this.socketVersion);
                            this.wsClient.EnableAutoSendPing = false;                             // #4 tkiley: Websocket4net client library initiates a websocket heartbeat, causes delivery problems
                            this.wsClient.Opened            += this.wsClient_OpenEvent;
                            this.wsClient.MessageReceived   += this.wsClient_MessageReceived;
                            this.wsClient.Error += this.wsClient_Error;

                            this.wsClient.Closed += wsClient_Closed;

                            this.wsClient.Open();
                        }
                    }

                    catch (Exception ex)
                    {
                        Debug.WriteLine(string.Format("Connect threw an exception...{0}", ex.Message));
                        this.OnErrorEvent(this, new ErrorEventArgs("SocketIO.Client.Connect threw an exception", ex));
                    }
                }
            }
        }
        void WSocket_OnClosed(WebSocket.WebSocket webSocket, ushort code, string message)
        {
            if (webSocket != wSocket)
            {
                return;
            }

            string reason = code.ToString() + " : " + message;

            HTTPManager.Logger.Information("WebSocketTransport", "WSocket_OnClosed " + reason);

            if (this.State == TransportStates.Closing)
            {
                this.State = TransportStates.Closed;
            }
            else
            {
                Connection.Error(reason);
            }
        }
示例#13
0
        void WSocket_OnError(WebSocket.WebSocket webSocket, string reason)
        {
            if (webSocket != wSocket)
            {
                return;
            }

            // On WP8.1, somehow we receive an exception that the remote server forcibly closed the connection instead of the
            // WebSocket closed packet... Also, even the /abort request didn't finished.
            if (this.State == TransportStates.Closing ||
                this.State == TransportStates.Closed)
            {
                base.AbortFinished();
            }
            else
            {
                HTTPManager.Logger.Error("WebSocketTransport", "WSocket_OnError " + reason);

                Connection.Error(reason);
            }
        }
示例#14
0
        public override void StartConnect()
        {
            HTTPManager.Logger.Verbose("WebSocketTransport", "StartConnect");

            if (this.webSocket == null)
            {
                Uri uri = BuildUri(this.connection.Uri);

                // Also, if there's an authentication provider it can alter further our uri.
                if (this.connection.AuthenticationProvider != null)
                {
                    uri = this.connection.AuthenticationProvider.PrepareUri(uri) ?? uri;
                }

                HTTPManager.Logger.Verbose("WebSocketTransport", "StartConnect connecting to Uri: " + uri.ToString());

                this.webSocket = new WebSocket.WebSocket(uri);
            }

#if !UNITY_WEBGL || UNITY_EDITOR
            // prepare the internal http request
            if (this.connection.AuthenticationProvider != null)
            {
                this.connection.AuthenticationProvider.PrepareRequest(webSocket.InternalRequest);
            }
#endif
            this.webSocket.OnOpen    += OnOpen;
            this.webSocket.OnMessage += OnMessage;
            this.webSocket.OnBinary  += OnBinary;
            this.webSocket.OnError   += OnError;
            this.webSocket.OnClosed  += OnClosed;

            this.webSocket.Open();

            this.State = TransportStates.Connecting;
        }
        public void StartConnect()
        {
            if (this.webSocket == null)
            {
                this.webSocket = new WebSocket.WebSocket(this.connection.Uri);
            }

#if !UNITY_WEBGL || UNITY_EDITOR
            // prepare the internal http request
            if (this.connection.AuthenticationProvider != null)
            {
                this.connection.AuthenticationProvider.PrepareRequest(webSocket.InternalRequest);
            }
#endif
            this.webSocket.OnOpen      += OnOpen;
            this.webSocket.OnMessage   += OnMessage;
            this.webSocket.OnBinary    += OnBinary;
            this.webSocket.OnErrorDesc += OnError;
            this.webSocket.OnClosed    += OnClosed;

            this.webSocket.Open();

            this.State = TransportStates.Connecting;
        }
        private void OnMessage(WebSocket.WebSocket webSocket, string data)
        {
            if (this.State == TransportStates.Connecting)
            {
                TryHandleHandshakeResponse(data);
                return;
            }

            this.messages.Clear();
            try
            {
                this.connection.Protocol.ParseMessages(data, ref this.messages);

                this.connection.OnMessages(this.messages);
            }
            catch (Exception ex)
            {
                HTTPManager.Logger.Exception("WebSocketTransport", "OnMessage(string)", ex);
            }
            finally
            {
                this.messages.Clear();
            }
        }
 private void OnError(WebSocket.WebSocket webSocket, string reason)
 {
     this.ErrorReason = reason;
     this.State       = TransportStates.Failed;
 }
示例#18
0
        /// <summary>
        /// Called when the web socket is open, and we are ready to send and receive data
        /// </summary>
        void OnOpen(WebSocket.WebSocket ws)
        {
            AddText("WebSocket Open!");

            this._input.interactable = true;
        }
示例#19
0
 /// <summary>
 /// Called when we received a text message from the server
 /// </summary>
 void OnMessageReceived(WebSocket.WebSocket ws, string message)
 {
     AddText(string.Format("Message received: <color=yellow>{0}</color>", message))
     .AddLeftPadding(20);
 }
示例#20
0
 /// <summary>
 /// Called when the web socket is open, and we are ready to send and receive data
 /// </summary>
 void OnOpen(WebSocket.WebSocket ws)
 {
     Text += string.Format("-WebSocket Open!\n");
 }
示例#21
0
 /// <summary>
 /// Called when we received a text message from the server
 /// </summary>
 void OnMessageReceived(WebSocket.WebSocket ws, string message)
 {
     Text += string.Format("-Message received: {0}\n", message);
 }
        private void OnClosed(WebSocket.WebSocket webSocket, ushort code, string message)
        {
            this.webSocket = null;

            this.State = TransportStates.Closed;
        }
示例#23
0
 /// <summary>
 /// Called when the web socket closed
 /// </summary>
 void OnClosed(WebSocket.WebSocket ws, UInt16 code, string message)
 {
     Text     += string.Format("-WebSocket closed! Code: {0} Message: {1}\n", code, message);
     webSocket = null;
 }
示例#24
0
        void OnGUI()
        {
            GUIHelper.DrawArea(GUIHelper.ClientArea, true, () =>
            {
                scrollPos = GUILayout.BeginScrollView(scrollPos);
                GUILayout.Label(Text);
                GUILayout.EndScrollView();

                GUILayout.Space(5);

                GUILayout.FlexibleSpace();

                address = GUILayout.TextField(address);

                if (webSocket == null && GUILayout.Button("Open Web Socket"))
                {
                    // Create the WebSocket instance
                    webSocket = new WebSocket.WebSocket(new Uri(address));

#if !UNITY_WEBGL
                    webSocket.StartPingThread = true;

#if !BESTHTTP_DISABLE_PROXY
                    if (HTTPManager.Proxy != null)
                    {
                        webSocket.InternalRequest.Proxy = new HTTPProxy(HTTPManager.Proxy.Address, HTTPManager.Proxy.Credentials, false);
                    }
#endif
#endif

                    // Subscribe to the WS events
                    webSocket.OnOpen    += OnOpen;
                    webSocket.OnMessage += OnMessageReceived;
                    webSocket.OnClosed  += OnClosed;
                    webSocket.OnError   += OnError;

                    // Start connecting to the server
                    webSocket.Open();

                    Text += "Opening Web Socket...\n";
                }

                if (webSocket != null && webSocket.IsOpen)
                {
                    GUILayout.Space(10);

                    GUILayout.BeginHorizontal();
                    msgToSend = GUILayout.TextField(msgToSend);

                    GUILayout.EndHorizontal();

                    if (GUILayout.Button("Send", GUILayout.MaxWidth(70)))
                    {
                        Text += "Sending message...\n";

                        // Send message to the server
                        webSocket.Send(msgToSend);
                    }

                    GUILayout.Space(10);

                    if (GUILayout.Button("Close"))
                    {
                        // Close the connection
                        webSocket.Close(1000, "Bye!");
                    }
                }
            });
        }