Exemple #1
0
        protected override void DidRemove()
        {
            base.DidRemove();

            OnClose?.Invoke();
        }
        public void Connect(string url)
        {
            socketUrl = url;
            try
            {
                socket = new ClientWebSocket();
                socket.ConnectAsync(new Uri(socketUrl), CancellationToken.None).Wait();
            }
            catch (AggregateException ex)
            {
                foreach (Exception exception in ex.InnerExceptions)
                {
                    string errMessage = exception.Message;
                    OnError?.Invoke("Error while connecting: Message : " + errMessage);
                    if (errMessage.Contains("Forbidden") && errMessage.Contains("403"))
                    {
                        OnClose?.Invoke();
                    }
                }
                return;
            }
            catch (Exception e)
            {
                OnError?.Invoke("Error while connecting. Message:  " + e.Message);
                return;
            }
            OnConnect?.Invoke();
            byte[] buffer = new byte[_bufferLength];

            Action <Task <WebSocketReceiveResult> > callback = null;

            try
            {
                callback = t =>
                {
                    try
                    {
                        byte[] tempBuff     = new byte[_bufferLength];
                        int    offset       = t.Result.Count;
                        bool   endOfMessage = t.Result.EndOfMessage;
                        // if chunk has even more data yet to recieve do that synchronously
                        while (!endOfMessage)
                        {
                            WebSocketReceiveResult result = socket.ReceiveAsync(new ArraySegment <byte>(tempBuff), CancellationToken.None).Result;
                            Array.Copy(tempBuff, 0, buffer, offset, result.Count);
                            offset      += result.Count;
                            endOfMessage = result.EndOfMessage;
                        }
                        // send data to process
                        OnData?.Invoke(buffer, offset, t.Result.MessageType.ToString());
                        // Again try to receive data
                        socket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None).ContinueWith(callback);
                    }
                    catch (Exception e)
                    {
                        if (IsConnected())
                        {
                            OnError?.Invoke("Error while recieving data. Message:  " + e.Message);
                        }
                        else
                        {
                            OnError?.Invoke("Lost ticker connection.");
                        }
                    }
                };

                // To start the receive loop in the beginning
                socket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None).ContinueWith(callback);
            }
            catch (Exception e)
            {
                OnError?.Invoke("Error while recieving data. Message:  " + e.Message);
            }
        }
Exemple #3
0
 public void Close()
 {
     OnClose?.Invoke();
 }
Exemple #4
0
 void Client_OnClose(object sender, EventArgs e)
 {
     clientOpen = false;
     Debug.LogError("CONNECTION CLOSED");
     OnClose?.Invoke(this, new EventArgs());
 }
Exemple #5
0
 protected void InvokeOnClose()
 {
     OnClose?.Invoke();
 }
 /// <summary>
 /// Closes the modal and invokes the <see cref="OnClose"/> event.
 /// </summary>
 public void Cancel()
 {
     OnClose?.Invoke(NoJSModalResult.Cancel());
 }
Exemple #7
0
 /// <summary>
 /// close notification by key
 /// </summary>
 /// <param name="key"></param>
 /// <returns></returns>
 public void Close(string key)
 {
     OnClose?.Invoke(key);
 }
 public WebSocketClient(IMessageInterpreter interpreter, string url)
 {
     _webSocket            = new WebSocketSharp.WebSocket(url);
     _webSocket.OnMessage += (sender, args) => OnMessage?.Invoke(sender, interpreter.InterpretMessage(args?.Data ?? ""));
     _webSocket.OnClose   += (sender, args) => OnClose?.Invoke(sender, args);
 }
Exemple #9
0
        /// <summary>
        /// Processes the message, updating our internal state and then invokes the events.
        /// </summary>
        /// <param name="message"></param>
        private void ProcessMessage(IMessage message)
        {
            if (message == null)
            {
                return;
            }
            switch (message.Type)
            {
            //We got a update, so we will update our current presence
            case MessageType.PresenceUpdate:
                lock (_sync)
                {
                    var pm = message as PresenceMessage;
                    if (pm != null)
                    {
                        //We need to merge these presences together
                        if (CurrentPresence == null)
                        {
                            CurrentPresence = pm.Presence;
                        }
                        else if (pm.Presence == null)
                        {
                            CurrentPresence = null;
                        }
                        else
                        {
                            CurrentPresence.Merge(pm.Presence);
                        }

                        //Update the message
                        pm.Presence = CurrentPresence;
                    }
                }

                break;

            //Update our configuration
            case MessageType.Ready:
                var rm = message as ReadyMessage;
                if (rm != null)
                {
                    lock (_sync)
                    {
                        Configuration = rm.Configuration;
                        CurrentUser   = rm.User;
                    }

                    //Resend our presence and subscription
                    SynchronizeState();
                }
                break;

            //Update the request's CDN for the avatar helpers
            case MessageType.JoinRequest:
                if (Configuration != null)
                {
                    //Update the User object within the join request if the current Cdn
                    var jrm = message as JoinRequestMessage;
                    if (jrm != null)
                    {
                        jrm.User.SetConfiguration(Configuration);
                    }
                }
                break;

            case MessageType.Subscribe:
                lock (_sync)
                {
                    var sub = message as SubscribeMessage;
                    Subscription |= sub.Event;
                }
                break;

            case MessageType.Unsubscribe:
                lock (_sync)
                {
                    var unsub = message as UnsubscribeMessage;
                    Subscription &= ~unsub.Event;
                }
                break;

            //We got a message we dont know what to do with.
            default:
                break;
            }

            //Invoke the appropriate methods
            switch (message.Type)
            {
            case MessageType.Ready:
                if (OnReady != null)
                {
                    OnReady.Invoke(this, message as ReadyMessage);
                }
                break;

            case MessageType.Close:
                if (OnClose != null)
                {
                    OnClose.Invoke(this, message as CloseMessage);
                }
                break;

            case MessageType.Error:
                if (OnError != null)
                {
                    OnError.Invoke(this, message as ErrorMessage);
                }
                break;

            case MessageType.PresenceUpdate:
                if (OnPresenceUpdate != null)
                {
                    OnPresenceUpdate.Invoke(this, message as PresenceMessage);
                }
                break;

            case MessageType.Subscribe:
                if (OnSubscribe != null)
                {
                    OnSubscribe.Invoke(this, message as SubscribeMessage);
                }
                break;

            case MessageType.Unsubscribe:
                if (OnUnsubscribe != null)
                {
                    OnUnsubscribe.Invoke(this, message as UnsubscribeMessage);
                }
                break;

            case MessageType.Join:
                if (OnJoin != null)
                {
                    OnJoin.Invoke(this, message as JoinMessage);
                }
                break;

            case MessageType.Spectate:
                if (OnSpectate != null)
                {
                    OnSpectate.Invoke(this, message as SpectateMessage);
                }
                break;

            case MessageType.JoinRequest:
                if (OnJoinRequested != null)
                {
                    OnJoinRequested.Invoke(this, message as JoinRequestMessage);
                }
                break;

            case MessageType.ConnectionEstablished:
                if (OnConnectionEstablished != null)
                {
                    OnConnectionEstablished.Invoke(this, message as ConnectionEstablishedMessage);
                }
                break;

            case MessageType.ConnectionFailed:
                if (OnConnectionFailed != null)
                {
                    OnConnectionFailed.Invoke(this, message as ConnectionFailedMessage);
                }
                break;

            default:
                //This in theory can never happen, but its a good idea as a reminder to update this part of the library if any new messages are implemented.
                Logger.Error("Message was queued with no appropriate handle! {0}", message.Type);
                break;
            }
        }
 private void _process_Exited(object sender, EventArgs e)
 {
     Dispose();
     OnClose.Invoke(sender, e);
 }
 public void Cancel()
 {
     CloseModal?.Invoke();
     OnClose?.Invoke(ModalResult.Cancel());
 }
Exemple #12
0
 private void DisconnectCallBack(IAsyncResult asyncResult)
 {
     clientSocket.EndDisconnect(asyncResult);
     OnClose?.Invoke();
 }
Exemple #13
0
        private async Task receiveLoop()
        {
            byte[] buffer = new byte[websocket_package_size];
            while (true)
            {
                string json = string.Empty;
                System.Net.WebSockets.WebSocketReceiveResult result;
                try
                {
                    if (ws == null)
                    {
                        return;
                    }
                    if (ws.State != System.Net.WebSockets.WebSocketState.Open)
                    {
                        OnClose?.Invoke("");
                        return;
                    }
                    result = await ws.ReceiveAsync(new ArraySegment <byte>(buffer), src.Token);

                    json = Encoding.UTF8.GetString(buffer.Take(result.Count).ToArray());
                    if (TryParseJSON(json))
                    {
                        var message = JsonConvert.DeserializeObject <SocketMessage>(json);
                        lock (_receiveQueue)
                        {
                            if (message != null)
                            {
                                _receiveQueue.Add(message);
                            }
                        }
                    }
                    else
                    {
                        if (TryParseJSON(tempbuffer + json))
                        {
                            var message = JsonConvert.DeserializeObject <SocketMessage>(tempbuffer + json);
                            lock (_receiveQueue)
                            {
                                if (message != null)
                                {
                                    _receiveQueue.Add(message);
                                }
                            }
                            tempbuffer = null;
                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(tempbuffer))
                            {
                                Log.Debug("FAILED: " + json);
                            }
                            tempbuffer += json;
                        }
                        if (!string.IsNullOrEmpty(tempbuffer) && tempbuffer.Length > (websocket_package_size * 2))
                        {
                            tempbuffer = null;
                        }
                    }
                    await ProcessQueue();
                }
                catch (System.Net.WebSockets.WebSocketException ex)
                {
                    if (ws.State != System.Net.WebSockets.WebSocketState.Open)
                    {
                        OnClose?.Invoke(ex.Message);
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(json))
                        {
                            Log.Error(json);
                        }
                        Log.Error(ex, "");
                        await Task.Delay(3000);

                        await this.Close();
                    }
                }
                catch (Exception ex)
                {
                    if (ws.State != System.Net.WebSockets.WebSocketState.Open)
                    {
                        OnClose?.Invoke(ex.Message);
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(json))
                        {
                            Log.Error(json);
                        }
                        Log.Error(ex, "");
                        await Task.Delay(3000);

                        //await this.Close();
                    }
                }
            }
        }
Exemple #14
0
 public void Dispose()
 {
     OnClose?.Invoke(this, LastError);
     Close();
 }
Exemple #15
0
 public void Close()
 {
     AudioManager.Instance.Play("Click2");
     OnClose?.Invoke();
     this.gameObject.SetActive(false);
 }
Exemple #16
0
 public void InvokeClose()
 {
     Connected      = false;
     DisconnectTime = DateTime.UtcNow;
     OnClose?.Invoke();
 }
Exemple #17
0
 /// <summary>
 /// 点击取消按钮回调此方法
 /// </summary>
 private Task OnClickClose()
 {
     CurrentTime = Value;
     OnClose?.Invoke();
     return(Task.CompletedTask);
 }
Exemple #18
0
 private void Disconnected(DisconnectionInfo obj)
 {
     OnClose?.Invoke(this, null);
 }
 /// <summary>
 /// Closes the modal and invokes the <see cref="OnClose"/> event with the specified <paramref name="modalResult"/>.
 /// </summary>
 /// <param name="modalResult"></param>
 public void Close(NoJSModalResult modalResult)
 {
     OnClose?.Invoke(modalResult);
 }
Exemple #20
0
 private void closeConnection()
 {
     OnClose?.Invoke();
     Console.WriteLine("socket closed: " + socket.RemoteEndPoint.ToString());
     socket.Dispose();
 }
Exemple #21
0
 protected override void onClientDisconnect(Connection client)
 {
     OnClose?.Invoke(client);
 }
        /// <summary>
        /// Connect to WebSocket
        /// </summary>
        public void Connect(string Url, Dictionary <string, string> headers = null)
        {
            _url = Url;
            try
            {
                // Initialize ClientWebSocket instance and connect with Url
                _ws = new ClientWebSocket();
                if (headers != null)
                {
                    foreach (string key in headers.Keys)
                    {
                        _ws.Options.SetRequestHeader(key, headers[key]);
                    }
                }
                _ws.ConnectAsync(new Uri(_url), CancellationToken.None).Wait();
            }
            catch (AggregateException e)
            {
                foreach (Exception ex in e.InnerExceptions)
                {
                    OnError?.Invoke("Error while connecting. Message: " + ex.Message, ex);
                    if (ex.Message.Contains("Forbidden") && ex.Message.Contains("403"))
                    {
                        OnClose?.Invoke();
                    }
                }
                return;
            }
            catch (Exception e)
            {
                OnError?.Invoke("Error while connecting. Message:  " + e.Message, e);
                return;
            }
            OnConnect?.Invoke();

            byte[] buffer = new byte[_bufferLength];
            Action <Task <WebSocketReceiveResult> > callback = null;

            try
            {
                //Callback for receiving data
                callback = t =>
                {
                    try
                    {
                        byte[] tempBuff     = new byte[_bufferLength];
                        int    offset       = t.Result.Count;
                        bool   endOfMessage = t.Result.EndOfMessage;
                        // if chunk has even more data yet to recieve do that synchronously
                        while (!endOfMessage)
                        {
                            WebSocketReceiveResult result = _ws.ReceiveAsync(new ArraySegment <byte>(tempBuff), CancellationToken.None).Result;
                            Array.Copy(tempBuff, 0, buffer, offset, result.Count);
                            offset      += result.Count;
                            endOfMessage = result.EndOfMessage;
                        }
                        // send data to process
                        OnData?.Invoke(buffer, offset, t.Result.MessageType.ToString());
                        // Again try to receive data
                        _ws.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None).ContinueWith(callback);
                    }
                    catch (Exception e)
                    {
                        if (IsConnected())
                        {
                            OnError?.Invoke("Error while recieving data. Message:  " + e.Message, e);
                        }
                        else
                        {
                            OnError?.Invoke("Lost ticker connection.", e);
                        }
                    }
                };

                // To start the receive loop in the beginning
                _ws.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None).ContinueWith(callback);
            }
            catch (Exception e)
            {
                OnError?.Invoke("Error while recieving data. Message:  " + e.Message, e);
            }
        }
 private void InnerOnClose()
 {
     OnClose?.Invoke();
 }
Exemple #24
0
 public void InvokeOnClose()
 {
     OnClose?.Invoke(this);
 }
Exemple #25
0
 private void WSClient_OnDisconnected(string ID, Exception ex)
 {
     OnClose?.Invoke(ex.Message);
 }
 public void Cancel()
 {
     CloseModal?.Invoke();
     OnClose?.Invoke(ModalResult.Cancel(this._modalType));
 }
Exemple #27
0
 void objASR_OnClose(object sender, CPqDCloseEventArgs e)
 {
     OnClose?.Invoke(this, e);
 }
 public void Close(ModalResult modalResult)
 {
     modalResult.ModalType = this._modalType;
     CloseModal?.Invoke();
     OnClose?.Invoke(modalResult);
 }
Exemple #29
0
 public void CloseModal() => OnClose?.Invoke();
Exemple #30
0
 public virtual void Close()
 {
     gameObject.SetActive(false);
     _opened = false;
     OnClose.Invoke(this);
 }