private void HandleOnError(object sender, WebSocketSharp.ErrorEventArgs e)
 {
     if (OnError != null)
     {
         OnError.Invoke(sender, new WebSocketErrorEventArgs(e.Message));
     }
 }
Beispiel #2
0
 public IEnumerator Connect()
 {
     m_Socket            = new WebSocketSharp.WebSocket(mUrl.ToString());
     m_Socket.OnMessage += (sender, e) =>
     {
         m_Messages.Enqueue(e.RawData);
     };
     m_Socket.OnOpen += (sender, e) =>
     {
         m_IsConnected = true;
         isConnected   = true;
     };
     m_Socket.OnError += (sender, e) =>
     {
         m_Error = e.Message;
         if (OnError != null)
         {
             OnError.Invoke(this, new ErrorEventArgs(m_Error));
         }
     };
     m_Socket.ConnectAsync();
     while (!m_IsConnected && m_Error == null)
     {
         yield return(0);
     }
     if (OnOpen != null)
     {
         OnOpen.Invoke(this, new EventArgs());
     }
 }
Beispiel #3
0
 internal void HandleOnError(string msg)
 {
     if (OnError != null)
     {
         OnError.Invoke(this, new ErrorEventArgs(msg));
     }
 }
 private void OnConsumerShutdown(object sender, ShutdownEventArgs e)
 {
     if (OnError != null)
     {
         OnError.Invoke(sender, e);
     }
 }
Beispiel #5
0
        public void OnMessage(object sender, MessageEventArgs e)
        {
            try
            {
                var data = MessagePackSerializer.Deserialize <CommandData>(e.RawData);
                if (data.Type == "error")
                {
                    // errors contain aditional attributes
                    var error = MessagePackSerializer.Deserialize <CoflnetExceptionTransmit>(e.RawData);
                    OnError.Invoke(new CoflnetException(error));
                    return;
                }

                onMessage?.Invoke(data);

                // confirm receival
                SendCommand(
                    CommandData.CreateCommandData <ReceiveConfirm, ReceiveConfirmParams>(
                        ConnectedServerId,
                        new ReceiveConfirmParams(data.SenderId, data.MessageId)));
            }
            catch (System.Exception ex)
            {
                Logger.Error(ex.Message);
            }
        }
 //
 private void SafeError(string message)
 {
     if (OnError != null)
     {
         OnError.Invoke(message);
     }
 }
Beispiel #7
0
        public void threadFunction()
        {
            try
            {
                /*var addr = Dns.GetHostAddresses(Host);
                 * if (addr.Length < 1)
                 *  throw new ArgumentException("Unknown host.");*/

                TcpListener = new TcpListener(IPAddress.Any, Port);
                TcpListener.Start();
                Running = true;
                while (true)
                {
                    try
                    {
                        var client = TcpListener.AcceptTcpClient();
                        Cytar.SetupSession(new TCPSession(client));
                    }
                    catch (SocketException)
                    {
                        Running = false;
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                if (OnError != null)
                {
                    OnError.Invoke(ex);
                }
            }
        }
 public virtual void RaiseException(MalformedLineException exception)
 {
     if (OnError != null)
     {
         OnError.Invoke(this, new EasyParserExceptionEventArgs(exception));
     }
 }
Beispiel #9
0
        /// <summary>
        /// poll for error processing
        /// this is because errors can come from a different thread
        /// </summary>
        private void Update()
        {
            if (errorEventArgs.Count <= 0)
            {
                return;
            }
            ErrorEventArgs error = errorEventArgs.Dequeue();

            if (socket != null)
            {
                socket.Close("Socket Error");
                socket = null;
            }
            connectionState = ConnectionState.Disconnected;
            if (OnClose != null)
            {
                OnClose.Invoke(this, new CloseEventArgs
                {
                    Reason   = "Socket Error: socket already closed",
                    WasClean = false
                });
            }
            if (OnError != null)
            {
                OnError.Invoke(this, error);
            }
        }
Beispiel #10
0
 protected void SetError(string errorText)
 {
     if (OnError != null)
     {
         OnError.Invoke(errorText);
     }
 }
Beispiel #11
0
        internal void Update()
        {
            while (eventArgsQueue.Count > 0)
            {
                EventArgs e;
                lock (eventArgsQueue)
                {
                    e = eventArgsQueue.Dequeue();
                }

                if (e is CloseEventArgs && OnClose != null)
                {
                    OnClose.Invoke(this, e as CloseEventArgs);
                }
                else if (e is OpenEventArgs && OnOpen != null)
                {
                    OnOpen.Invoke(this, e as OpenEventArgs);
                }
                else if (e is MessageEventArgs && OnMessage != null)
                {
                    OnMessage.Invoke(this, e as MessageEventArgs);
                }
                else if (e is ErrorEventArgs && OnError != null)
                {
                    OnError.Invoke(this, e as ErrorEventArgs);
                }
            }
        }
 private void fireOnError(string errdesc)
 {
     if (OnError != null)
     {
         OnError.Invoke(errdesc);
     }
 }
Beispiel #13
0
 /// <summary>
 /// Try setting a port for server. Returns true if the port is available.
 /// </summary>
 /// <param name="port"></param>
 /// <param name="setOpenPortIfFailed">If true, will automatically set an open port when the input one is not available.</param>
 /// <returns>return true if succeeded.</returns>
 public bool TrySetPort(int port = OpenPortFlag, bool setOpenPortIfFailed = false)
 {
     if (isListening)
     {
         if (OnError != null)
         {
             OnError.Invoke(this, new ConnectionErrorEventArgs("Server", "Cannot change the port when server is running."));
         }
         return(false);
     }
     if (port == OpenPortFlag)
     {
         Port = NetworkUtil.GetOpenPort();
         return(true);
     }
     else
     {
         if (NetworkUtil.IsPortAvailable(port))
         {
             Port = port;
             return(true);
         }
         else
         {
             if (setOpenPortIfFailed)
             {
                 TrySetPort();
             }
             return(false);
         }
     }
 }
Beispiel #14
0
 private void RaiseError(string message)
 {
     if (OnError != null)
     {
         OnError.Invoke(this, new WebSocketErrorEventArgs(message));
     }
 }
Beispiel #15
0
        /// <summary>
        /// Handles exceptions
        /// </summary>
        /// <param name="message"></param>
        internal static void ExceptionHandle(NetIncomingMessage message, String reason)
        {
            Handshake.Contents contents;
            switch ((message.SenderConnection.Tag as Handshake).HandshakeState)
            {
            case Handshake.State.Failed:
                contents = Handshake.Contents.Error;
                OnError.Invoke(reason);
                break;

            case Handshake.State.Expired:
                contents = Handshake.Contents.Expired;
                OnExpired.Invoke(reason);
                break;

            case Handshake.State.Denied:
                contents = Handshake.Contents.Denied;
                OnDenied.Invoke(reason);
                break;

            default:
                contents = Handshake.Contents.Error;
                OnError.Invoke(reason);
                break;
            }
            var result = Create(message.SenderConnection, contents);

            result.Write(reason);
            message.SenderConnection.SendMessage(result, NetDeliveryMethod.ReliableUnordered, 0);
        }
        private void UpdateEntry(Entry entry)
        {
            try
            {
                entry.CoroutineProcessor.Update();
            }
            catch (Exception ex)
            {
                entry.CoroutineProcessor.Stop();
                entry.CoroutineProcessor.Exception = ex;

                if (entry.HandlerError != null)
                {
                    entry.HandlerError.Invoke(entry.Target, ex);
                }
                else if (OnError != null)
                {
                    OnError.Invoke(entry.Target, ex);
                }
                else
                {
                    throw;
                }
            }
        }
 public async Task GetError(string err)
 {
     if (OnError != null)
     {
         await OnError.Invoke(err);
     }
 }
Beispiel #18
0
        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="data">数据</param>
        public bool Send(byte[] data)
        {
            if (_socket != null && _socket.Connected)
            {
                try
                {
                    _socket.Send(data);
                    return(true);
                }
                catch (Exception ex)
                {
                    if (OnError != null)
                    {
                        OnError.Invoke(this, new MsgEventArgs()
                        {
                            Msg = ex.Message
                        });
                    }

                    return(false);
                }
            }
            else
            {
                if (OnError != null)
                {
                    OnError.Invoke(this, new MsgEventArgs()
                    {
                        Msg = "发送数据失败,Tcp 未建立连接。"
                    });
                }

                return(false);
            }
        }
Beispiel #19
0
        public void Flush()
        {
            if (_rawCommand != null)
            {
                var rawCommand = _rawCommand;
                rawCommand.TraceMessage = _traceMessage.ToString();
                _traceMessage.Clear();

                try
                {
                    var parsedCommand = _parser.Parse(rawCommand);
                    OnCommand?.Invoke(this, parsedCommand);
                }
                catch (Exception ex)
                {
                    if (OnError != null)
                    {
                        OnError.Invoke(this, ex);
                    }
                    else
                    {
                        throw;
                    }
                }
            }
        }
        public async Task OpenAsync()
        {
            await ExecuteRetryPolicy();

            subscriptions.Clear();

            if (channel != null)
            {
                try
                {
                    channel.Dispose();
                    channel = null;
                    client  = null;
                    logger?.LogDebug("Disposed internal channel.");
                }
                catch (Exception ex)
                {
                    logger?.LogError(ex, "Fault disposing internal channel.");
                }
            }

            try
            {
                channel = new WebSocketClientChannel(endpointUrl, securityToken, "mqtt", new WebSocketConfig(),
                                                     CancellationToken.None);
                client = new PiraeusMqttClient(new MqttConfig(180), channel);
                client.OnChannelError       += Client_OnChannelError;
                client.OnChannelStateChange += Client_OnChannelStateChange;

                string         sessionId = Guid.NewGuid().ToString();
                ConnectAckCode code      = await client.ConnectAsync(sessionId, "JWT", securityToken, 180);

                if (code != ConnectAckCode.ConnectionAccepted)
                {
                    logger?.LogWarning($"Vrtu channel connect return code = '{code}'.");
                    OnError.Invoke(this,
                                   new ChannelErrorEventArgs(channel.Id,
                                                             new Exception($"VRtu channel failed to open with code = {code}")));
                }
                else
                {
                    logger?.LogInformation("Vrtu channel connected.");
                    try
                    {
                        diag = new DiagnosticsChannel(config, client, logger);
                        diag.StartAsync().GetAwaiter();
                    }
                    catch (Exception ex)
                    {
                        diag = null;
                        logger?.LogError(ex, "Diagnostics on Vrtu channel faulted.");
                    }
                }
            }
            catch (Exception ex)
            {
                logger?.LogError(ex, "Fault opening MQTT client channel.");
            }
        }
Beispiel #21
0
        protected override void OnReceived(byte[] data)
        {
            if (!_isHandSharked)
            {
                _cache.AddRange(data);

                try
                {
                    var    handShakeText = Encoding.UTF8.GetString(_cache.ToArray());
                    string key           = string.Empty;
                    Regex  reg           = new Regex(@"Sec\-WebSocket\-Accept:(.*?)\r\n");
                    Match  m             = reg.Match(handShakeText);
                    if (string.IsNullOrEmpty(m.Value))
                    {
                        throw new Exception("回复中不存在 Sec-WebSocket-Accept");
                    }
                    key            = Regex.Replace(m.Value, @"Sec\-WebSocket\-Accept:(.*?)\r\n", "$1").Trim();
                    _isHandSharked = true;
                }
                catch (Exception ex)
                {
                    OnError.Invoke(UserToken.ID, ex);
                }
            }
            else
            {
                var coder = (WSCoder)UserToken.Unpacker;

                coder.Unpack(data, (d) =>
                {
                    var wsProtocal = (WSProtocal)d;
                    switch (wsProtocal.Type)
                    {
                    case (byte)WSProtocalType.Close:
                        base.Disconnect();
                        break;

                    case (byte)WSProtocalType.Pong:
                        var date = DateTime.Parse(Encoding.UTF8.GetString(wsProtocal.Content));
                        OnPong?.Invoke(date);
                        break;

                    case (byte)WSProtocalType.Binary:
                    case (byte)WSProtocalType.Text:
                    case (byte)WSProtocalType.Cont:
                        OnMessage?.Invoke((WSProtocal)d);
                        break;

                    case (byte)WSProtocalType.Ping:
                        ReplyPong();
                        break;

                    default:
                        var error = string.Format("收到未定义的Opcode={0}", d.Type);
                        break;
                    }
                }, null, null);
            }
        }
Beispiel #22
0
 public override void OnPhotonJoinRoomFailed(object[] codeAndMsg)
 {
     if (OnError != null)
     {
         OnError.Invoke(this, new ErrorEventArgs(ErrorType.ErrorJoiningRoom, "Error Joining Room. " + codeAndMsg[1]));
     }
     SwitchProgressLabelVisibility(false);
 }
Beispiel #23
0
 private void Browser_LoadError(object sender, LoadErrorEventArgs e)
 {
     this.Invoke((Action) delegate
     {
         OnError.Invoke(e.ErrorText, new EventArgs());
         this.Close();
     });
 }
Beispiel #24
0
 private void timeout_Tick(object sender, EventArgs e)
 {
     this.Invoke((Action) delegate
     {
         OnError.Invoke("Timeout", new EventArgs());
         this.Close();
     });
 }
Beispiel #25
0
 /// <summary>
 /// 当异常时
 /// </summary>
 /// <param name="obj">异常</param>
 private void OnSocketError(object obj)
 {
     lastException = obj as Exception;
     if (OnError != null)
     {
         OnError.Invoke(this, (Exception)obj);
     }
 }
Beispiel #26
0
 public void onError(AndroidJavaObject exception)
 {
     if (OnError != null)
     {
         OnError.Invoke(exception);
     }
     Debug.Log("ENTER callback onError: " + exception);
 }
Beispiel #27
0
 private void RetryTask(string data)
 {
     // we dont count for retry because eac task retries itself
     if (OnError != null)
     {
         OnError.Invoke(data);
     }
 }
Beispiel #28
0
        public void Failed(NetworkErrorType errorType, string errorMsg, NetworkPacket packet)
        {
            packet.Error(errorType, errorMsg);

            if (OnError != null)
            {
                OnError.Invoke(errorType, packet);
            }
        }
Beispiel #29
0
        private async Task <LoadMoreItemsResult> LoadMoreItemsAsync(uint count, CancellationToken cancellationToken)
        {
            uint resultCount = 0;

            _cancellationToken = cancellationToken;

            try
            {
                if (!_cancellationToken.IsCancellationRequested)
                {
                    IEnumerable <IType> data = null;
                    try
                    {
                        IsLoading = true;
                        data      = await LoadDataAsync(count, _cancellationToken);
                    }
                    catch (OperationCanceledException)
                    {
                        // The operation has been canceled using the Cancellation Token.
                    }
                    catch (Exception ex) when(OnError != null)
                    {
                        OnError.Invoke(ex);
                    }

                    if (data != null && data.Any() && !_cancellationToken.IsCancellationRequested)
                    {
                        resultCount = (uint)data.Count();

                        var reversed = data.Reverse();
                        foreach (var item in reversed)
                        {
                            Insert(0, item);
                        }
                    }
                    else
                    {
                        HasMoreItems = false;
                    }
                }
            }
            finally
            {
                IsLoading = false;

                if (_refreshOnLoad)
                {
                    _refreshOnLoad = false;
                    await RefreshAsync();
                }
            }

            return(new LoadMoreItemsResult {
                Count = resultCount
            });
        }
Beispiel #30
0
        private async void StartHandshakeWithClient(SocketStream client)
        {
            try
            {
                var message = "";
                while (client.socket.Connected)
                {
                    var buffer    = new byte[2048];
                    var bytesRead = await client.stream.ReadAsync(buffer, 0, buffer.Length);

                    if (bytesRead == 0)
                    {
                        break;
                    }

                    message += Encoding.UTF8.GetString(buffer, 0, bytesRead);
                    if (message.Contains(Terminator.HTTP))
                    {
                        Console.WriteLine($"WebSocketServer: A HandShake received from {client.IP}:{client.Port}...");
                        //var messages = message.Split(new[] { HTTP_TERMINATOR }, StringSplitOptions.RemoveEmptyEntries);
                        if (Regex.IsMatch(message, "^GET", RegexOptions.IgnoreCase))
                        {
                            // 1. Obtain the value of the "Sec-WebSocket-Key" request header without any leading or trailing whitespace
                            // 2. Concatenate it with "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" (a special GUID specified by RFC 6455)
                            // 3. Compute SHA-1 and Base64 hash of the new value
                            // 4. Write the hash back as the value of "Sec-WebSocket-Accept" response header in an HTTP response
                            string swk            = Regex.Match(message, "Sec-WebSocket-Key: (.*)").Groups[1].Value.Trim();
                            string swka           = swk + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
                            byte[] swkaSha1       = System.Security.Cryptography.SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(swka));
                            string swkaSha1Base64 = Convert.ToBase64String(swkaSha1);

                            // HTTP/1.1 defines the sequence CR LF as the end-of-line marker
                            var outgoingMessage = "HTTP/1.1 101 Switching Protocols\r\n" +
                                                  "Connection: Upgrade\r\n" +
                                                  "Upgrade: websocket\r\n" +
                                                  "Sec-WebSocket-Accept: " + swkaSha1Base64 + "\r\n\r\n";
                            byte[] response = Encoding.UTF8.GetBytes(outgoingMessage);
                            Console.WriteLine($"WebSocketServer: Replying to HandShake for {client.IP}:{client.Port}...");
                            await client.stream.WriteAsync(response, 0, response.Length);
                        }
                        else
                        {
                            throw new Exception("WebSocketServer: Incoming websocket handshake message was not in the right format.");
                        }

                        StartReceivingFromClient(client);
                        break;
                    }
                }
            }
            catch (Exception exception)
            {
                OnError.Invoke(this, exception);
                Disconnect(client);
            }
        }