예제 #1
0
        /// <summary>
        /// 当接收到消息
        /// </summary>
        /// <param name="obj">消息内容</param>
        private void OnSocketMessage(object obj)
        {
            var data = (byte[])obj;

            Exception ex;
            var       packet = receiveState.Input(data, out ex);

            if (ex != null)
            {
                OnSocketError(ex);
                Disconnect();
                return;
            }

            if (packet == null)
            {
                return;
            }

            lock (heartBeatState)
            {
                heartBeatState.Reset();
            }

            if (OnMessage != null)
            {
                OnMessage.Invoke(this, packet);
            }
        }
예제 #2
0
 private void HandleOnMessage(object sender, MessageWebSocketMessageReceivedEventArgs args)
 {
     if (OnMessage == null)
     {
         return;
     }
     try {
         using (var reader = args.GetDataReader()) {
             if (args.MessageType == SocketMessageType.Utf8)
             {
                 string text = reader.ReadString(reader.UnconsumedBufferLength);
                 OnMessage.Invoke(sender, new WebSocketMessageEventArgs(text));
             }
             else if (args.MessageType == SocketMessageType.Binary)
             {
                 byte[] data = new byte[reader.UnconsumedBufferLength];
                 reader.ReadBytes(data);
                 OnMessage.Invoke(sender, new WebSocketMessageEventArgs(data));
             }
         }
     } catch (Exception ex) {
         WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult);
         RaiseError(status.ToString() + " " + ex.Message);
     }
 }
예제 #3
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);
                }
            }
        }
예제 #4
0
        private void HandleImpl(QueryRequest request)
        {
            var result   = _engine.Execute(request.Query);
            var response = new QueryResponse(result, request.Id);

            OnMessage.Invoke(response);
        }
예제 #5
0
 /// <summary>
 /// 收到消息时
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="topic"></param>
 /// <param name="message"></param>
 void mqttClient_OnMessageArrived(object sender, string topic, MqttMessage message)
 {
     if (this.OnMessage != null)
     {
         OnMessage.Invoke(message);
     }
 }
예제 #6
0
파일: RClient.cs 프로젝트: bagezifu/SAEA
 protected override void OnReceived(byte[] data)
 {
     UserToken.Unpacker.Unpack(data, (content) =>
     {
         OnMessage.Invoke(content.Content);
     }, null, null);
 }
예제 #7
0
        private void HandleImpl(CommandRequest request)
        {
            var result   = _engine.Execute(request.Command);
            var response = new CommandResponse(result, request.Id);

            OnMessage.Invoke(response);
        }
예제 #8
0
    public void OpenWebsocket(string connectionId, List <KeyValuePair <string, string> > websocketheaders)
    {
        socket = new WebSocket(connectionId, websocketheaders);

        socket.OnMessage += (sender, e) =>
        {
            if (OnMessage != null)
            {
                OnMessage.Invoke(e.Data);
            }
        };

        socket.OnOpen += (sender, e) =>
        {
            if (OnOpen != null)
            {
                OnOpen.Invoke();
            }
        };

        socket.OnError += (sender, e) =>
        {
            Debug.LogError(e.Exception);
        };

        socket.Connect();
    }
예제 #9
0
 internal void HandleOnMessageStr(string data)
 {
     if (OnMessage != null)
     {
         OnMessage.Invoke(this, new MessageEventArgs(Opcode.Text, data));
     }
 }
예제 #10
0
 public void InvokeOnMessage(string data)
 {
     if (OnMessage != null)
     {
         OnMessage.Invoke(data);
     }
 }
예제 #11
0
 internal void HandleOnMessage(byte[] rawData)
 {
     if (OnMessage != null)
     {
         OnMessage.Invoke(this, new MessageEventArgs(Opcode.Binary, rawData));
     }
 }
예제 #12
0
 private void HandleOnMessage(Opcode opcode, byte[] rawData)
 {
     if (OnMessage != null)
     {
         OnMessage.Invoke(this, new MessageEventArgs(opcode, rawData));
     }
 }
예제 #13
0
 protected override void OnReceived(byte[] data)
 {
     UserToken.Unpacker.Unpack(data, (content) =>
     {
         OnMessage.Invoke(content.Content);
     }, null, null);
     OnActived.Invoke(DateTimeHelper.Now);
 }
예제 #14
0
 private static void LogMessage(object sender, LogSeverity sev, string format, params object[] args)
 {
     if (OnMessage != null && (LogSeverityLevel & sev) != 0)
     {
         var message = (args != null && args.Length > 0) ? string.Format(format, args) : format;
         OnMessage.Invoke(sender, new LogEventArgs(sev, message));
     }
 }
예제 #15
0
        private async Task HandleImpl(CommandRequest request)
        {
            var result = await _engine.ExecuteUntyped(request.Command);

            var response = new CommandResponse(result, request.Id);

            OnMessage.Invoke(response);
        }
예제 #16
0
 private void HandleOnMessage(object sender, WebSocketSharp.MessageEventArgs e)
 {
     if (OnMessage != null)
     {
         var args = e.IsBinary ? new WebSocketMessageEventArgs(e.RawData) : new WebSocketMessageEventArgs(e.Data);
         OnMessage.Invoke(sender, args);
     }
 }
        /// <summary>
        /// Called when the twitch client receives a message
        /// </summary>
        private void OnMessageReceived(object sender, OnMessageReceivedArgs e)
        {
            var chatMessage = e.ChatMessage;

            var evnt = new OnMessageArgs();

            evnt.Message  = chatMessage.Message.Trim();
            evnt.ClientId = chatMessage.UserId;
            OnMessage.Invoke(this, evnt);
        }
예제 #18
0
 protected override void OnReceived(byte[] data)
 {
     OnActived.Invoke(DateTimeHelper.Now.AddSeconds(60));
     if (data != null)
     {
         this.UserToken.Coder.Pack(data, null, (content) =>
         {
             OnMessage.Invoke(Encoding.UTF8.GetString(content.Content));
         }, null);
     }
 }
예제 #19
0
파일: Channel.cs 프로젝트: davuxcom/IRCLib
 internal void MessageRcv(User u, string msg)
 {
     if (OnMessage != null /* && UseMessageHandler */)
     {
         OnMessage.Invoke(u, msg);
     }
     else
     {
         //Messages.Enqueue(new object[] { u, msg });
     }
 }
        /// <summary>
        /// Called when the twitch client receives a message
        /// </summary>
        private void OnMessageReceived(object sender, OnMessageReceivedArgs e)
        {
            var chatMessage = e.ChatMessage;

            var evnt = new OnMessageArgs();

            evnt.Message  = chatMessage.Message.Trim();
            evnt.ClientId = chatMessage.UserId;
            evnt.Username = chatMessage.Username.ToLower(); // lower case the username to allow case-insensitive comparisons
            OnMessage.Invoke(this, evnt);
        }
예제 #21
0
        private void SendMatchingEvents(JournalRecord journalRecord, bool isLocal, IEnumerable <Event> events)
        {
            var matchingEvents = events
                                 .Where(e => _subscriptions.Values.Any(matcher => matcher.IsMatch(e)))
                                 .ToArray();

            if (matchingEvents.Length > 0)
            {
                _logger.LogTrace("Sending {0} events", matchingEvents.Length);
                OnMessage.Invoke(new EventsRaised(matchingEvents));
            }
        }
 public void MessageReceivedCallback(UInt32 hLocalMessageBroadcastPartner, UInt32 sendingPartnerId, IntPtr msgData, UInt32 msgLength, IntPtr customData)
 {
     if (OnMessage != null)
     {
         try {
             OnMessage.Invoke(sendingPartnerId, msgData, msgLength);
         } catch (Exception e) {
             //catch all in order not to f**k up LocalMessageBroadcast
             //the implementor should make sure this desn't throw exceptions in the first place
         }
     }
 }
예제 #23
0
        public Task ProcessMessage(Message message, CancellationToken token)
        {
            var eventArgs = new MessageEventArgs
            {
                Message           = message,
                CancellationToken = token,
                Client            = Client
            };

            OnMessage.Invoke(this, eventArgs);
            return(Task.CompletedTask);
        }
예제 #24
0
 private void DealException(BaseMethod method, ErrorTypes type, Exception ex, string msg = null)
 {
     if (OnMessage != null)
     {
         OnMessage.Invoke(method, new MessageArgs()
         {
             ErrorType = type,
             Message   = msg ?? ex.GetBaseException().Message
         });
     }
     method.ErrorType = type;
     method.ErrorMsg  = msg ?? ex.GetBaseException().Message;
 }
예제 #25
0
        /// <summary>
        /// 线程执行方法
        /// </summary>
        private void DoWork()
        {
            while (IsThreadWorking || HasMessage())
            {
                if (!_msgSemaphore.WaitOne(1))
                {
                    continue;
                }

                var msg = PickMessage();
                OnMessage.Invoke(msg);
            }
        }
예제 #26
0
 public void Handle(Message message)
 {
     try
     {
         dynamic d = message;
         HandleImpl(d);
     }
     catch (Exception ex)
     {
         _logger.LogError(ex, "Error handling message: " + message);
         OnMessage.Invoke(new ExceptionResponse(message, ex));
     }
 }
예제 #27
0
 public byte[] Recv()
 {
     if (m_Messages.Count == 0)
     {
         return(null);
     }
     byte[] mDeq = m_Messages.Dequeue();
     if (OnMessage != null)
     {
         OnMessage.Invoke(this, new MessageEventArgs(mDeq));
     }
     return(mDeq);
 }
예제 #28
0
        /// <summary>
        /// 接收消息
        /// </summary>
        private async void Receive()
        {
            var result = await this.udpClient.ReceiveAsync();

            var msg = Encodes.UTF8NoBOM.GetString(result.Buffer);
            var iep = result.RemoteEndPoint;

            OnMessage.Invoke(this, msg, iep);
            if (listening)
            {
                Receive();
            }
        }
예제 #29
0
        public void Start(string apiBind)
        {
            var httpBind = apiBind.ToString();

            if (string.IsNullOrWhiteSpace(httpBind))
            {
                OnMessage.Invoke(this, new MessageArgs(string.Format("API-bind is null or empty, using default {0}", DefaultAPIPath)));
                httpBind = DefaultAPIPath;
            }

            if (!httpBind.StartsWith("http://") || httpBind.StartsWith("https://"))
            {
                httpBind = "http://" + httpBind;
            }
            if (!httpBind.EndsWith("/"))
            {
                httpBind += "/";
            }

            if (!int.TryParse(httpBind.Split(':')[2].TrimEnd('/'), out int port))
            {
                throw new ArgumentException("Invalid port provided.");
            }

            var tempIPAddress = httpBind.Split("//")[1].Split(':')[0];

            if (!IPAddress.TryParse(tempIPAddress, out IPAddress ipAddress))
            {
                throw new ArgumentException("Invalid IP address provided.");
            }

            using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                try { socket.Bind(new IPEndPoint(ipAddress, port)); }
                catch (Exception) { throw new ArgumentException(string.Format("API failed to bind to {0}", apiBind)); }
            };

            try
            {
                _Listener = new HttpListener();
                _Listener.Prefixes.Add(httpBind);
                _IsOngoing = true;

                Task.Run(() => Process(_Listener));
            }
            catch (Exception)
            {
                _IsOngoing = false;
                throw new ArgumentException("An error has occured while starting API.");
            }
        }
예제 #30
0
 private void FixedUpdate()
 {
     if (receivedPacketQueue.Count > 0 && onPacketReceive != null)
     {
         lock (receiveQueueLock) {
             Queue <Packet> .Enumerator iter = receivedPacketQueue.GetEnumerator();
             while (iter.MoveNext())
             {
                 onPacketReceive.Invoke(iter.Current);
             }
             receivedPacketQueue.Clear();
         }
     }
 }