private async void Communicate(TCPConnection connection)
    {
        try {
            while (connection.active)
            {
                List <byte> data = await connection.Receive();

                string channel = data.ReadString();
                if (channel == "disconnection")
                {
                    connection.active = false;
                }
                else
                {
                    //received a message from the host!
                    onMessageReception.Invoke(connection, channel, data);
                }
            }
            onConnectionEnd.Invoke(connection);
            hosts.Remove(connection);
        }catch (SocketException se) {
            Haze.Logger.LogError("[TCPClient] Socket Exception (" + se.ErrorCode + "), cannot communicate with host: " + se.ToString(), this);
        }catch (Exception e) {
            Haze.Logger.LogError("[TCPClient] Error, cannot communicate with host: " + e.ToString(), this);
        }
    }
Esempio n. 2
0
        private void SafeInvokeMessageRecevied(MessageReceivedEventArgs eventArgs)
        {
            if (this.RemoteMessage == null)
            {
                return; //No Listeners
            }

            MessageReceivedEvent listener = null;

            Delegate[] dels = this.RemoteMessage.GetInvocationList();

            foreach (Delegate del in dels)
            {
                try
                {
                    listener = (MessageReceivedEvent)del;
                    listener.Invoke(eventArgs);
                }
                catch (Exception)
                {
                    //Could not reach the destination, so remove it
                    //from the list
                    this.RemoteMessage -= listener;
                }
            }
        }
Esempio n. 3
0
        private async void PacketReceivedEventHandler(object sender, PacketReceivedEventArgs e)
        {
            if (!Message.IsMessageContentType(e.Packet.ContentType))
            {
                await ErrorAsync("Packet content is not a message!").ConfigureAwait(false);

                return;
            }

// TODO: exceptions here?

            Logger.Debug("Attempting to parse a message...");
            Message message = await Message.DeSerializeAsync(e.Packet.ContentType, e.Packet.Encoding, e.Packet.Content, 0, e.Packet.ContentLength, MessageFactory).ConfigureAwait(false);

            if (null == message)
            {
                await ErrorAsync("Failed to parse a message!").ConfigureAwait(false);

                return;
            }

            Logger.Debug($"{message.Type} message parsed!");
            MessageReceivedEvent?.Invoke(this, new MessageReceivedEventArgs
            {
                Message = message
            }
                                         );
        }
Esempio n. 4
0
        private void WaitForData()
        {
            while (true)
            {
                try
                {
                    var         data    = new byte[GlobalConfig.Size];
                    var         builder = new StringBuilder();
                    UserMessage receivedObject;

                    do
                    {
                        var bytes = Stream.Read(data, 0, data.Length);
                        receivedObject = JsonSerializer.Deserialize <UserMessage>(Encoding.UTF8.GetString(data, 0, bytes));
                        builder.Append(receivedObject);
                    }while (Stream.DataAvailable);

                    var message = builder.ToString();
                    Console.WriteLine(message);
                    MessageReceivedEvent?.Invoke(receivedObject, this);
                }
                catch (JsonException ex)
                {
                    Console.WriteLine(ex.Message);
                }
                catch
                {
                    Console.WriteLine($"Подключение {Id} прервано!");
                    Disconnect();
                    break;
                }
            }
        }
        private async Task ReadAsync(Package package)
        {
            // побуферно читаем сообщения, что позволяет не ограничиваться его размером

            var readBytes = await _pipeServer.ReadAsync(package.Buffer, 0, package.Buffer.Length);

            if (readBytes > 0)
            {
                byte[] result;
                if (_pipeServer.IsMessageComplete)
                {
                    result = new byte[readBytes];
                    Array.Copy(package.Buffer, 0, result, 0, readBytes);
                }
                else
                {
                    result = package.Buffer;
                }

                package.Result.AddRange(result);

                // если не дочитали...
                if (!_pipeServer.IsMessageComplete)
                {
                    // ...то читаем следующий буфер
                    await ReadAsync(package);
                }
                else
                {
                    using (var stream = new MemoryStream(package.Result.ToArray()))
                    {
                        var message = Serializer.Deserialize <T>(stream);

                        MessageReceivedEvent?.Invoke(this,
                                                     new MessageReceivedEventArgs <T>
                        {
                            ClientId = responceClientId,
                            Message  = message
                        });
                    }
                    await ReadAsync(new Package());
                }
            }
            // Если прочитано 0 байт, то клиент вероятно отключился
            else
            {
                if (!_isStopping)
                {
                    Stop();
                    ClientDisconnectedEvent?.Invoke(
                        this,
                        new ClientDisconnectedEventArgs {
                        ClientId = responceClientId
                    });
                }
            }
        }
Esempio n. 6
0
    /// <summary>
    /// Message event as decoded string
    /// </summary>
    /// <param name="message">Decoded message</param>
    public void MessageReceived(string message)
    {
        //Debug.Log ("UDP:Received:"+message);

        //Message Received event for listeners
        if (MessageReceivedEvent != null)
        {
            MessageReceivedEvent.Invoke(message);
        }
    }
Esempio n. 7
0
        private async Task ReceiveMessage(MqttApplicationMessageReceivedEventArgs e)
        {
            Debug.WriteLine("### RECEIVED APPLICATION MESSAGE ###");
            Debug.WriteLine($"+ Topic = {e.ApplicationMessage.Topic}");
            Debug.WriteLine($"+ Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
            Debug.WriteLine($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}");
            Debug.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}");
            Debug.WriteLine("");

            MessageReceivedEvent?.Invoke(e);
        }
Esempio n. 8
0
 protected virtual void OnMessage(RemoteServer server, MessageEventArgs args)
 {
     MessageEvent?.Invoke(server, args);
     if (args.Sent)
     {
         MessageSentEvent?.Invoke(server, args);
     }
     else
     {
         MessageReceivedEvent?.Invoke(server, args);
     }
 }
Esempio n. 9
0
        private void OnMessageReceived(object o, BasicDeliverEventArgs e)
        {
            Console.WriteLine("Message received");
            if (!string.Equals(API.DemoMessage.Descriptor.Name, e.BasicProperties.Type,
                               StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            var message = API.DemoMessage.Parser.ParseFrom(e.Body.ToArray());

            MessageReceivedEvent?.Invoke(this, new MessageReceivedEventArgs(message));
        }
        private void HandleMessage(string msg)
        {
            MediaResult result = MediaResult.FromJson(msg);

            if (result.isOk())
            {
                MessageReceivedEvent?.Invoke(result);
            }
            else
            {
                Debug.Print("error: " + result.ToString());
            }
            Debug.Print(result.ToString());
        }
Esempio n. 11
0
 private void Run()
 {
     while (true)
     {
         Message m = _messageQueue.Receive();
         Stock   s = m.Body as Stock;
         if (s != null)
         {
             if (s.Index.Equals(_indexFilter))
             {
                 MessageReceivedEvent.Invoke(this, new StockMessageEventArgs(s));
             }
         }
     }
 }
Esempio n. 12
0
        private void BeginReceive()
        {
            receiveTask = Task.Factory.StartNew(async() =>
            {
                while (!ShutDown && Client.Connected)
                {
                    var data    = new byte[client.ReceiveBufferSize];
                    var count   = await stream.ReadAsync(data, 0, client.ReceiveBufferSize);
                    var message = Encoding.ASCII.GetString(data, 0, count);

                    var address = (IPEndPoint)client.Client.RemoteEndPoint;
                    MessageReceivedEvent?.Invoke(new Message(message, address), message.Split('|'));
                }
            });
        }
Esempio n. 13
0
        public void OnMessageReceived(IntPtr lc, IntPtr room, IntPtr message)
        {
            var peer_address = ChatModule.linphone_chat_room_get_peer_address(room);

            if (peer_address.IsNonZero())
            {
                var addressStringPtr = CallModule.linphone_address_as_string(peer_address);
                var chatMessagePtr   = ChatModule.linphone_chat_message_get_text(message);

                string addressString, chatMessage;
                if (MarshalingExtensions.TryConvert(addressStringPtr, out addressString) && MarshalingExtensions.TryConvert(chatMessagePtr, out chatMessage))
                {
                    MessageReceivedEvent?.Invoke(addressString, chatMessage);
                }
            }
        }
Esempio n. 14
0
        private void WaitConnection()
        {
            _ = Task.Run(() =>
            {
                while (true)
                {
                    ps_ = new NamedPipeServerStream(GameServerPipeName, PipeDirection.InOut);
                    ps_.WaitForConnection();

                    using (var sr = new StreamReader(ps_))
                    {
                        var message = sr.ReadToEnd();
                        MessageReceivedEvent?.Invoke(this, new MessageReceivedEventArgs(message));
                    }
                }
            });
        }
Esempio n. 15
0
        private void OnInputFileChanged(object sender, FileSystemEventArgs fileSystemEventArgs)
        {
            if (inputEventRaised)
            {
                // We get 2 events for every save of the file...
                inputEventRaised = false;
                return;
            }

            inputEventRaised = true;

            var inputText = File.ReadAllText(inputFile);

            logger.LogDebug($"Input Received: {inputText}");

            MessageReceivedEvent?.Invoke(this, inputText);
        }
Esempio n. 16
0
    private async void Communicate(TCPConnection connection)
    {
        while (connection.active)
        {
            List <byte> data = await connection.Receive();

            if (data.Count > 0)
            {
                string channel = data.ReadString();
                if (channel == "disconnection")
                {
                    connection.active = false;
                }
                else
                {
                    //received a message from the host!
                    onMessageReception.Invoke(connection, channel, data);
                }
            }
            else
            {
                Haze.Logger.LogWarning("Received data with length == 0 from connection " + connection);
                connection.active = false;
            }
        }

        //Attempt to send a "disconnection" message before closing
        {
            List <byte> data = new List <byte>();
            data.WriteString("disconnection");
            try {
                await connection.Send(data);
            } catch (Exception e) {
                //nevermind.
            }
        }

        onConnectionEnd.Invoke(connection);
        users.Remove(connection);
        if (!connection.UDP)
        {
            connection.client.Close();
        }
    }
Esempio n. 17
0
        private void SendMessageReceived(UdpReceiveResult result)
        {
            var bytes = result.Buffer;

            if (bytes?.Any() ?? false)
            {
                var content = Encoding.ASCII.GetString(
                    bytes: bytes.ToArray(),
                    index: 0,
                    count: bytes.Count()).TrimEnd(EndChar);

                if (!string.IsNullOrWhiteSpace(content))
                {
                    MessageReceivedEvent?.Invoke(
                        sender: this,
                        e: new MessageReceivedArgs(content));
                }
            }
        }
Esempio n. 18
0
        /// <summary>
        /// Invokes a event
        /// </summary>
        /// <typeparam name="T">The event</typeparam>
        /// <param name="message">The message</param>
        public void RaiseServerEvent <T>(T message) where T : IServerEvent
        {
            Type messageType = typeof(T);

            if (m_MessageAwaiters.ContainsKey(messageType))
            {
                MessageReceivedEvent awaiter = m_MessageAwaiters[messageType];
                awaiter.Invoke((object)message);
            }

            if (m_ServerEventHandlers.ContainsKey(messageType))
            {
                m_ServerEventHandlers[messageType].DynamicInvoke(message);
            }

            if (m_GroupServerEventHandlers.ContainsKey(messageType))
            {
                m_GroupServerEventHandlers[messageType].Invoke(this, message);
            }
        }
Esempio n. 19
0
        // Through this method, we can fire the event in a thread safe manor from everywhere inside the class.
        private void IncommingMessage(NewMessageEventArgs e)
        {
            lock (messageReceivedEventPadlock) {
                // When the server is notified it will raise its own event with the same message and id.
                MessageReceivedEvent?.Invoke(id, e);

                // ?. is called a null conditional operator.
                // If the target (here, messageReceivedEvent) is null, it returns null
                // Otherwise it calls the specified member.
                // In normal syntax this is (explicitely):

                // MessageReceivedHandler handler = messageReceivedEvent;
                // if (handler == null) return null;
                // else return messageReceivedEvent.Invoke(id, new NewMessageEventArgs(message));

                // For this case it would be:
                // MessageReceivedHandler handler = messageReceivedEvent;
                // if (handler != null) messageReceivedEvent.Invoke(id, new NewMessageEventArgs(message));

                // as returns from operators are ignored the value is not assigned to anything.
            }
        }
Esempio n. 20
0
        private void ReciveMessages()
        {
            while (true)
            {
                try
                {
                    var         builder = new StringBuilder();
                    var         data    = new byte[GlobalConfig.GlobalConfig.Size];
                    UserMessage receivedObject;

                    do
                    {
                        var bytes = Stream.Read(data, 0, data.Length);
                        receivedObject = JsonSerializer.Deserialize <UserMessage>(Encoding.UTF8.GetString(data, 0, bytes));

                        builder.Append(receivedObject);
                    }while (Stream.DataAvailable);

                    MessageReceivedEvent?.Invoke(receivedObject);

                    var message = builder.ToString();
                    Console.WriteLine(message);
                }

                catch (JsonException ex)
                {
                    Console.WriteLine(ex.Message);
                    break;
                }

                catch (Exception ex) when(ex is SocketException || ex is IOException)
                {
                    Console.WriteLine($"Error: {ex.Message} = {ex.GetType()} Подключение прервано!");
                    RunEventDelegatesAsync(ConnectionLostEvent?.GetInvocationList());
                    break;
                }
            }
        }
Esempio n. 21
0
 private void HandleMessageReceived(object sender, MessageReceivedEventArgs state)
 {
     MessageReceivedEvent?.Invoke(state.Message);
 }
Esempio n. 22
0
 protected virtual void OnMessageReceivedEvent(SocketEventArgs e)
 {
     MessageReceivedEvent?.Invoke(this, e);
 }
Esempio n. 23
0
 /// <summary>
 /// 触发事件
 /// </summary>
 public void Raise_MessageReceivedEvent(object sender, decimal number)
 {
     MessageReceivedEvent?.Invoke(sender, number);
 }
Esempio n. 24
0
        private async void ProcessClientStream(TcpClient client)
        {
            var stream = client.GetStream();

            while (!ShutDown)
            {
                if (client.Client != null && client.Connected)
                {
                    //if (client.Client.Poll(TimeOutTime, SelectMode.SelectRead))
                    //{
                    //    Player player = null;
                    //    byte[] buff = new byte[1];
                    //    if (client.Client.Receive(buff, SocketFlags.Peek) == 0)
                    //    {
                    //        Client Disconnected
                    //        foreach (var pl in GameStore.Instance.Game.PlayerList)
                    //        {
                    //            if (pl.Key.Client == client)
                    //            {
                    //                player = pl.Key;
                    //                Console.WriteLine("A player : " + pl.Key.PlayerAddress + " has disconnected");
                    //                pl.Value.Dispose();
                    //            }
                    //        }
                    //        if (player != null) GameStore.Instance.Game.PlayerList.Remove(player);
                    //        return;
                    //    }
                    //    else
                    //    {

                    //    }
                    //     = GameStore.Instance.Game.GetPlayerFromIpEndPoint((IPEndPoint)client.Client.RemoteEndPoint);
                    //    Console.WriteLine("A player : " + pl.PlayerAddress + " has disconnected");
                    //    pl.Value.Wait();
                    //}
                    var data = new byte[client.ReceiveBufferSize];
                    int count;
                    try
                    {
                        count = await stream.ReadAsync(data, 0, client.ReceiveBufferSize);
                    }
                    //A player Just Disconnected Sudden Disconnection
                    //The listener tried to read from a stream that was suddenly broked
                    catch (IOException)
                    {
                        DisconnectClient(client);
                        //Wait for a new client to connect
                        StartAwaitClients();
                        return;
                    }
                    //Client is Still Connected
                    var message = Encoding.ASCII.GetString(data, 0, count);
                    //Message Received just after client closes his stream
                    if (message == CodeMessages.PLAYER_DISCONNECTED)
                    {
                        //GameStore.Instance.Game.GetPlayer()
                        DisconnectClient(client);
                        //Wait for a new client to connect
                        StartAwaitClients();
                        return;
                    }
                    var address = (IPEndPoint)client.Client.RemoteEndPoint;
                    MessageReceivedEvent?.Invoke(new Message(message, address));
                }
            }
        }
Esempio n. 25
0
 internal void RaiseOnMessageReceived(BotWideMessageArguments args)
 {
     OnMessageReceived?.Invoke(args);
 }
Esempio n. 26
0
 private void MessageReceivedHandler(object sender, MessageReceivedEventArgs <T> eventArgs)
 {
     _synchronizationContext.Post(
         e => MessageReceivedEvent?.Invoke(this, (MessageReceivedEventArgs <T>)e),
         eventArgs);
 }
Esempio n. 27
0
        private void OnMessageReceived(object sender, MessageReceivedEventArgs args)
        {
            var message = Encoding.ASCII.GetString(args.Data);

            MessageReceivedEvent?.Invoke(this, message);
        }
Esempio n. 28
0
 private void OnClientData(int id, ArraySegment <byte> data)
 {
     MessageReceivedEvent?.Invoke(id, data);
 }
Esempio n. 29
0
 private void LinphoneWrapper_MessageReceivedEvent(string from, string message)
 {
     MessageReceivedEvent?.Invoke(from, message);
 }
 private void MessageReceivedHandle(Message message)
 {
     MessageReceivedEvent?.Invoke(this, new MessageReceivedEventArgs(message));
 }