Ejemplo n.º 1
0
 private void DealWithFeedBack(ReadWriteObject rwObj, int count)
 {
     byte[] b = new byte[count];
     Array.Copy(rwObj.ReadBytes, 0, b, 0, count);
     SendData(b);
     OnReceiveMessage?.Invoke(Message.Parser.ParseFrom(b));
 }
Ejemplo n.º 2
0
 private void Connect()
 {
     connection.On <string, string>("ReceiveMessage", (user, message) =>
     {
         OnReceiveMessage?.Invoke(user, message);
     });
 }
Ejemplo n.º 3
0
 /// <summary>
 /// Runs in background clientReceiveThread; Listens for incomming data.
 /// </summary>
 private void ListenForData()
 {
     try
     {
         socketConnection = new TcpClient(Hostname, Port);
         Byte[] bytes = new Byte[1024];
         while (true)
         {
             // Get a stream object for reading
             using (NetworkStream stream = socketConnection.GetStream())
             {
                 int length;
                 // Read incomming stream into byte arrary.
                 while ((length = stream.Read(bytes, 0, bytes.Length)) != 0)
                 {
                     var incommingData = new byte[length];
                     Array.Copy(bytes, 0, incommingData, 0, length);
                     // Convert byte array to string message.
                     string serverMessage = Encoding.ASCII.GetString(incommingData);
                     OnReceiveMessage?.Invoke(serverMessage);
                 }
             }
         }
     }
     catch (SocketException socketException)
     {
         Debug.Log("Socket exception: " + socketException);
         socketConnection = null;
     }
 }
Ejemplo n.º 4
0
 private void WebSocketClient_OnReceiveMessage(WebSocketClient.Core.WebSocketClient webSocketClient, string message)
 {
     if (OnReceiveMessage != null)
     {
         OnReceiveMessage.Invoke(this, Newtonsoft.Json.JsonConvert.DeserializeObject <ReceiveMessage>(message));
     }
 }
Ejemplo n.º 5
0
 internal void CheckMessages()
 {
     while (ReceiveMessagesQueue.TryDequeue(out var message))
     {
         OnReceiveMessage?.Invoke(message);
     }
 }
Ejemplo n.º 6
0
        public void Client_OnReceive(IAsyncResult asyncResult)
        {
            int receivedSize = Client.EndReceive(asyncResult);

            if (receivedSize > 0)
            {
                ReceivedContent.Append(Encoding.ASCII.GetString(Buffer, 0, receivedSize));

                string content          = ReceivedContent.ToString();
                int    indexOfEndOfFile = content.IndexOf(EOF);

                while (indexOfEndOfFile > -1)
                {
                    var currentContent = content.Substring(0, indexOfEndOfFile);

                    content         = content.Substring(indexOfEndOfFile + EOF.Length);
                    ReceivedContent = new StringBuilder(content);

                    OnReceiveMessage?.Invoke(currentContent);

                    indexOfEndOfFile = content.IndexOf(EOF);
                }
            }

            if (!Client.Connected)
            {
                OnDisconnected?.Invoke();
            }
            else if (!CancellationToken.IsCancellationRequested)
            {
                Client.BeginReceive(Buffer, 0, BufferSize, SocketFlags.None, new AsyncCallback(Client_OnReceive), null);
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// 异步发送消息
        /// </summary>
        /// <param name="tcpClient">客户端套接字</param>
        /// <param name="message">发送消息</param>
        public void AsynSend(string message)
        {
            Message m = new Message
            {
                Name    = tcpClient.LocalEndPoint.ToString(),
                Content = message
            };

            byte[] sendBytes;
            using (MemoryStream stream = new MemoryStream())
            {
                // Save the person to a stream
                m.WriteTo(stream);
                sendBytes = stream.ToArray();
            }
            tcpClient.BeginSend(sendBytes, 0, sendBytes.Length, SocketFlags.None, asyncResult =>
            {
                //完成发送消息
                int length = tcpClient.EndSend(asyncResult);
                OnReceiveMessage?.Invoke(new Message()
                {
                    Name = "Client", Content = message
                });
            }, null);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// 异步递归接受消息
        /// </summary>
        /// <returns></returns>
        public async Task ReceiveMessageAsync()
        {
            ArraySegment <byte>    receiveBuffer = new ArraySegment <byte>(new byte[1024]);
            CancellationToken      cancel        = new CancellationToken();
            WebSocketReceiveResult webSocketReceiveResult;

            try
            {
                webSocketReceiveResult = await ClientWebSocket.ReceiveAsync(receiveBuffer, cancel);
            }
            catch (Exception ex)
            {
                PrintHelper.printError(ex, log);
                await CloseAsync(WebSocketCloseStatus.ProtocolError, "WebSocket 连接异常" + GetExceptionMessge(ex));

                return;
            }
            byte[] bytes = new byte[webSocketReceiveResult.Count];
            Array.Copy(receiveBuffer.Array, bytes, webSocketReceiveResult.Count);
            if (!webSocketReceiveResult.CloseStatus.HasValue)
            {
                if (OnReceiveMessage != null)
                {
                    OnReceiveMessage.Invoke(this, Encoding.GetString(bytes));
                }
                await ReceiveMessageAsync();
            }
            else
            {
                PrintHelper.PrintInfo($"连接被关闭:服务器关闭码【{webSocketReceiveResult.CloseStatus.Value}】,原因【{webSocketReceiveResult.CloseStatusDescription}】", log);
                await CloseAsync(webSocketReceiveResult.CloseStatus.Value, webSocketReceiveResult.CloseStatusDescription);
            }
        }
Ejemplo n.º 9
0
    static int set_Receive(IntPtr L)
    {
        object o = null;

        try
        {
            o = ToLua.ToObject(L, 1);
            SingleWeb        obj       = (SingleWeb)o;
            OnReceiveMessage arg0      = null;
            LuaTypes         funcType2 = LuaDLL.lua_type(L, 2);

            if (funcType2 != LuaTypes.LUA_TFUNCTION)
            {
                arg0 = (OnReceiveMessage)ToLua.CheckObject(L, 2, typeof(OnReceiveMessage));
            }
            else
            {
                LuaFunction func = ToLua.ToLuaFunction(L, 2);
                arg0 = DelegateFactory.CreateDelegate(typeof(OnReceiveMessage), func) as OnReceiveMessage;
            }

            obj.Receive = arg0;
            return(0);
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e, o == null ? "attempt to index Receive on a nil value" : e.Message));
        }
    }
        public void Execute(OnReceiveMessage pipelineEvent)
        {
            var parser = pipelineEvent.Pipeline.State.Get <MsmqUriParser>();
            var tx     = pipelineEvent.Pipeline.State.Get <MessageQueueTransaction>();

            try
            {
                pipelineEvent.Pipeline.State.Add(
                    pipelineEvent.Pipeline.State.Get <MessageQueue>("queue")
                    .Receive(pipelineEvent.Pipeline.State.Get <TimeSpan>("timeout"), tx));
            }
            catch (MessageQueueException ex)
            {
                if (ex.MessageQueueErrorCode == MessageQueueErrorCode.IOTimeout)
                {
                    pipelineEvent.Pipeline.State.Add <Message>(null);
                    return;
                }

                if (ex.MessageQueueErrorCode == MessageQueueErrorCode.AccessDenied)
                {
                    MsmqQueue.AccessDenied(_log, parser.Path);
                }

                _log.Error(string.Format(MsmqResources.GetMessageError, parser.Uri, ex.Message));

                throw;
            }
        }
Ejemplo n.º 11
0
 public Subscriber(OnReceiveMessage <T> aCallback, bool aStartSubscribing)
 {
     myOnReceiveMessage = aCallback;
     if (aStartSubscribing == true)
     {
         Subscribe();
     }
 }
Ejemplo n.º 12
0
        private void Consumer_Received1(object sender, BasicDeliverEventArgs e)
        {
            var message = Encoding.UTF8.GetString(e.Body);

            OnReceiveMessage?.Invoke(this, new MessageEventArgs(message));

            _channel.BasicAck(deliveryTag: e.DeliveryTag, multiple: false);
        }
Ejemplo n.º 13
0
        public void Init(string url, bool useHttps)
        {
            var port = string.Empty;

            // ios || android
            if (url.Equals("localhost") || url.Equals("10.0.2.2"))
            {
                port = useHttps ? ":5001" : ":5000";
            }
            string completeUrl = string.Format("http{0}://{1}{2}/hubs/chat",
                                               useHttps ? "s" : string.Empty, url, port);

            hubConnection = new HubConnectionBuilder().WithUrl(completeUrl).Build();

            // Closing connection
            hubConnection.Closed += async(error) =>
            {
                OnConnectionClosed?.Invoke(this, new MessageEventArgs("", "Closing connection"));
                connected = false;

                // Reconnect
                await Task.Delay(3000);

                try
                {
                    await ConnectAsync();
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e);
                }
            };

            // Joining/leaving a group
            hubConnection.On <string>("EnterOrLeave", (message) =>
            {
                OnEnterOrLeave?.Invoke(this, new MessageEventArgs(message, message));
            });

            hubConnection.On <string>("Enter", (user) =>
            {
                OnEnterOrLeave?.Invoke(this, new MessageEventArgs(user, $"{user} joined"));
            });

            hubConnection.On <string>("Leave", (user) =>
            {
                OnEnterOrLeave?.Invoke(this, new MessageEventArgs(user, $"{user} left"));
            });

            // Receive message
            hubConnection.On <string, string>("ReceiveMessage", (user, message) =>
            {
                OnReceiveMessage?.Invoke(this, new MessageEventArgs(user, message));
            });
        }
Ejemplo n.º 14
0
    /// <summary>
    /// Remove a listener
    /// </summary>
    /// <param name="action">The action to remove</param>
    public void RemoveListener(OnReceiveMessage action)
    {
        listeners.Remove(action);

                #if SHOW_DEBUG_INFO
        if (onUpdateListeners != null)
        {
            onUpdateListeners(listeners);
        }
                #endif
    }
Ejemplo n.º 15
0
        /// <summary>
        /// Raised when a new line was received.
        /// </summary>
        /// <param name="sender">Sender.</param>
        /// <param name="e">E.</param>
        private static void NewLineReceived(object sender, CommandEventArgs e)
        {
                        #if DEBUG
            Console.WriteLine(@"Received > " + e.Command.CommandString());
                        #endif

            if (OnReceiveMessage != null)
            {
                OnReceiveMessage.Invoke(null, new CommunicationArgs(e.Command.CommandString()));
            }
            LastCommunication = DateTime.Now;
        }
Ejemplo n.º 16
0
    public Client(TcpClient client, OnReceiveMessage onReceiveMessage)
    {
        this.onReceiveMessage = onReceiveMessage;
        ns = client.GetStream();

        streamReader = new StreamReader(ns);

        ThreadStart ts = new ThreadStart(StartTread);

        tread = new Thread(ts);

        tread.Start();
    }
Ejemplo n.º 17
0
 public static void ActOnMessage(Message message)
 {
     if (message.Type == MsgType.Ack)
     {
         Log.Info(_tag, $"Received client ack of {message.Content}");
     }
     else
     {
         OnReceiveMessage.Raise(message);
         var doThis = ParseMessageToAction(message);
         doThis?.Invoke(BaseActivity.CurrentActivity); // Note - nothing (currently) actually *uses* the argument of doThis; passing it the current activity is basically a placeholder here.
     }
 }
Ejemplo n.º 18
0
 /// <summary>
 /// 异步连接客户端回调函数
 /// </summary>
 /// <param name="tcpClient"></param>
 private void AsynRecive()
 {
     byte[] data = new byte[2048];
     tcpClient.BeginReceive(data, 0, data.Length, SocketFlags.None, asyncResult =>
     {
         int length = tcpClient.EndReceive(asyncResult);
         if (length > 0)
         {
             Message message = Message.Parser.ParseFrom(data, 0, length);
             OnReceiveMessage?.Invoke(message);
         }
         AsynRecive();
     }, null);
 }
Ejemplo n.º 19
0
        public async void MessageListener()
        {
            byte[] intBuffer = new byte[IntBytes];
            while (!disposed && networkStream != null)
            {
                try
                {
                    int lengthBytesRead =
                        await networkStream.ReadAsync(intBuffer, 0, IntBytes, disposeCancellationSource.Token);

                    // Socket has been disconnected
                    if (lengthBytesRead <= 0)
                    {
                        Disconnect();
                        break;
                    }

                    int length = BitConverter.ToInt32(intBuffer, 0);

                    // Handle empty messages asap
                    if (length == 0)
                    {
                        OnReceiveMessage?.Invoke(this, "");
                    }
                    else if (length < 0)
                    {
                        OnReceiveMessage?.Invoke(this, null);
                    }

                    byte[] messageBuffer    = new byte[length];
                    int    messageBytesRead =
                        await networkStream.ReadAsync(messageBuffer, 0, length, disposeCancellationSource.Token);

                    // Socket has been disconnected
                    if (messageBytesRead <= 0)
                    {
                        Disconnect();
                        break;
                    }

                    string message = Encoding.GetString(messageBuffer, 0, length);

                    OnReceiveMessage?.Invoke(this, message);
                }
                catch (Exception e)
                {
                    Program.LogDebugException(nameof(MessageListener), e);
                }
            }
        }
Ejemplo n.º 20
0
    /// <summary>
    /// Listen to the message with the given id
    /// </summary>
    /// <param name="id">id of the message to listen for</param>
    /// <param name="action">The action to run when the message is received</param>
    public void AddListener(string id, OnReceiveMessage action)
    {
        if (!listeners.ContainsKey(action))
        {
            listeners.Add(action, id);
        }

                #if SHOW_DEBUG_INFO
        if (onUpdateListeners != null)
        {
            onUpdateListeners(listeners);
        }
                #endif
    }
Ejemplo n.º 21
0
 /// <summary>
 /// Tcp协议异步连接服务器
 /// </summary>
 public Client AsynConnect()
 {
     //主机IP
     tcpClient.BeginConnect(serverIp, asyncResult =>
     {
         tcpClient.EndConnect(asyncResult);
         OnReceiveMessage?.Invoke(new Message()
         {
             Name = "Client", Content = $"Connected {serverIp.ToString()}"
         });
         AsynRecive();
     }, null);
     return(this);
 }
Ejemplo n.º 22
0
        private void Enqueue(IConsoleLogMessage message)
        {
            if (message.Type > MaxLogLevel)
            {
                return;
            }

            if (LogHistory.Count > MaxLogRegister)
            {
                LogHistory.Dequeue();
            }
            LogHistory.Enqueue(message);

            OnReceiveMessage?.Invoke(message);
        }
Ejemplo n.º 23
0
        private void AcceptTcpClientCallback(IAsyncResult ar)
        {
            TcpListener myListener = ar.AsyncState as TcpListener;
            TcpClient   client     = myListener.EndAcceptTcpClient(ar);

            OnReceiveMessage?.Invoke(new Message()
            {
                Name = "Server", Content = $"Connected {client.Client.RemoteEndPoint.ToString()}"
            });
            ReadWriteObject readWriteObject = new ReadWriteObject(client);

            rwoList.Add(readWriteObject);
            readWriteObject.BeginRead(ReadCallback);
            AcceptConnect();
        }
Ejemplo n.º 24
0
        public void Init(string urlRoot, bool useHttps)
        {
            random = new Random();

            var port = (urlRoot == "localhost" || urlRoot == "10.0.2.2") ? (useHttps ? ":5001" : ":5000") : String.Empty;

            var url = $"http{(useHttps ? "s" : String.Empty)}://{urlRoot}{port}/hub/chat";

            hubConnection = new HubConnectionBuilder()
                            .WithUrl(url)
                            .Build();

            hubConnection.Closed += async(error) =>
            {
                OnConnectionClosed?.Invoke(this, new MessageEventArgs("Connection closed...", String.Empty));
                IsConnected = false;
                await Task.Delay(random.Next(0, 5) * 1000);

                try
                {
                    await ConnectAsync();
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex);
                }
            };

            hubConnection.On <string, string>("ReceiveMessage", (user, message) =>
            {
                OnReceiveMessage?.Invoke(this, new MessageEventArgs(message, user));
            });

            hubConnection.On <string>("Entered", (user) =>
            {
                OnEnteredOrExisted?.Invoke(this, new MessageEventArgs($"{user} entered...", user));
            });

            hubConnection.On <string>("Left", (user) =>
            {
                OnEnteredOrExisted?.Invoke(this, new MessageEventArgs($"{user} left...", user));
            });

            hubConnection.On <string>("EnterOrLeft", (message) =>
            {
                OnEnteredOrExisted?.Invoke(this, new MessageEventArgs(message, message));
            });
        }
Ejemplo n.º 25
0
 private void Poll()
 {
     while (Enabled)
     {
         //Get next message
         var deliveryArgs = _subscription.Next();
         //Deserialize message
         var message   = Encoding.Default.GetString(deliveryArgs.Body);
         var dsMessage = JsonConvert.DeserializeObject <T>(message);
         OnReceiveMessage.Invoke(this, new RecieveMessageArgs <T> {
             Data = dsMessage
         });
         //Acknowledge message is processed
         _subscription.Ack(deliveryArgs);
     }
 }
Ejemplo n.º 26
0
    static int get_Receive(IntPtr L)
    {
        object o = null;

        try
        {
            o = ToLua.ToObject(L, 1);
            SingleWeb        obj = (SingleWeb)o;
            OnReceiveMessage ret = obj.Receive;
            ToLua.Push(L, ret);
            return(1);
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e, o == null ? "attempt to index Receive on a nil value" : e.Message));
        }
    }
Ejemplo n.º 27
0
        public void ListenMessage()
        {
            IPEndPoint IpFrom = new IPEndPoint(IPAddress.Any, 0);

            while (true)
            {
                var rcvMessage = System.Text.Encoding.UTF8.GetString(UdpClient.Receive(ref IpFrom));
                OnReciveMessageEventArgs args = new OnReciveMessageEventArgs
                {
                    IP      = IpFrom.Address.ToString(),
                    Message = rcvMessage
                };
                if (OnReceiveMessage != null)
                {
                    OnReceiveMessage.Invoke(this, args);
                }
            }
        }
Ejemplo n.º 28
0
 private void ReceiveCallback(IAsyncResult ar)
 {
     try
     {
         if (ar.IsCompleted)
         {
             IPEndPoint epp  = new IPEndPoint(IPAddress.Any, 0);
             byte[]     buff = socket.EndReceive(ar, ref epp);
             ar.AsyncWaitHandle.Close();
             OnReceiveMessage?.Invoke(epp, buff);
             //socket.Send(back, back.Length, epp);
             socket.BeginReceive(ReceiveCallback, null);
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.ToString());
     }
 }
Ejemplo n.º 29
0
        internal void ReceiveMessage(BoundUserInterfaceMessage wrappedMessage, IPlayerSession session)
        {
            if (!_subscribedSessions.Contains(session))
            {
                Logger.DebugS("go.comp.ui", "Got message from session not subscribed to us.");
                return;
            }

            switch (wrappedMessage)
            {
            case CloseBoundInterfaceMessage _:
                _subscribedSessions.Remove(session);
                break;

            default:
                OnReceiveMessage?.Invoke(wrappedMessage);
                break;
            }
        }
Ejemplo n.º 30
0
        public fBase(IJobAction jobAction)
        {
            StoreMessages = new QueueThreadSafe <Message>();
            JobAction     = jobAction;
            //store.f_form_Add(this);
            //this.FormClosing += (se, ev) => { store.f_form_Remove(this); };

            timer_api = new System.Threading.Timer(new System.Threading.TimerCallback((obj) =>
            {
                IFORM form = (IFORM)obj;
                if (StoreMessages.Count > 0)
                {
                    Message m = StoreMessages.Dequeue(null);
                    if (m != null)
                    {
                        OnReceiveMessage?.Invoke(form, m);
                    }
                }
            }), this, 100, 100);
        }
	/// <summary>
	/// Listen to the message with the given id
	/// </summary>
	/// <param name="id">id of the message to listen for</param>
	/// <param name="action">The action to run when the message is received</param>
	public void AddListener (string id, OnReceiveMessage action) {

		if (!listeners.ContainsKey (action))
			listeners.Add (action, id);

		#if SHOW_DEBUG_INFO
		if (onUpdateListeners != null)
			onUpdateListeners (listeners);
		#endif
	}
	/// <summary>
	/// Remove a listener
	/// </summary>
	/// <param name="action">The action to remove</param>
	public void RemoveListener (OnReceiveMessage action) {

		listeners.Remove (action);

		#if SHOW_DEBUG_INFO
		if (onUpdateListeners != null)
			onUpdateListeners (listeners);
		#endif
	}
    public Client(TcpClient client , OnReceiveMessage onReceiveMessage)
    {
        this.onReceiveMessage = onReceiveMessage;
        ns = client.GetStream();

        streamReader = new StreamReader(ns);

        ThreadStart ts = new ThreadStart(StartTread);

        tread = new Thread(ts);

        tread.Start();
    }