예제 #1
0
 protected void InvokeDataReceived(BaseIpcServer server, IpcEventArgs args)
 {
     if (!args.HasErrors)
     {
         OnDataReceived?.Invoke(server, args);
     }
 }
        private void ProcessClientSocket(Socket socket)
        {
            while (socket.Available == 0)
            {
                Thread.Yield();
            }

            var count  = socket.Available;
            var buffer = new byte[count];

            socket.Receive(buffer);
            socket.Send(__responseBytes);
            socket.Close();

            using (var stream = new StreamReader(new MemoryStream(buffer)))
            {
                var exit    = false;
                var headers = new List <HttpHeader>();
                var query   = string.Empty;
                while (!stream.EndOfStream && !exit)
                {
                    var line = stream.ReadLine();
                    if (string.IsNullOrEmpty(line))
                    {
                        exit = true;
                    }
                    else
                    {
                        if (line.Contains(':'))
                        {
                            var parts = line.Split(':');
                            headers.Add(new HttpHeader(parts[0], parts[1]));
                        }
                        else
                        {
                            query = line;
                            if (!query.StartsWith("POST"))
                            {
                                return;
                            }
                        }
                    }
                }

                byte[] messageBytes = null;

                var contentLength = headers.FirstOrDefault(x => x.Name == "Content-Length");
                if (!stream.EndOfStream && contentLength.Name != null)
                {
                    if (int.TryParse(contentLength.Value, out var contentBytesCount))
                    {
                        messageBytes = new byte[contentBytesCount];
                        Array.Copy(buffer, buffer.Length - contentBytesCount, messageBytes, 0, contentBytesCount);
                    }
                }

                var result = new HttpPostData(headers.ToArray(), messageBytes ?? new byte[0], query);
                OnDataReceived?.Invoke(result);
            }
        }
예제 #3
0
    private void StartListening()
    {
        try {
            client       = server.AcceptTcpClient();
            clientStream = client.GetStream();
            OnClientConnected.Invoke();

            stringBuilder = new StringBuilder();
            while (started)
            {
                byte[] readBuffer = new byte[client.ReceiveBufferSize];
                int    bytesRead  = clientStream.Read(readBuffer, 0, readBuffer.Length);
                stringBuilder.Append(Encoding.ASCII.GetString(readBuffer, 0, bytesRead));
                string content = stringBuilder.ToString();

                while (content.IndexOf("\n") > -1)
                {
                    int    end     = content.IndexOf("\n");
                    string message = content.Substring(0, end);
                    content = content.Substring(end + 1);
                    OnDataReceived.Invoke(message);
                }

                stringBuilder = new StringBuilder(content);
            }
        } catch (SocketException e) {
            Console.WriteLine("SocketException: {0}", e);
        } finally {
            server.Stop();
        }
    }
예제 #4
0
        /// <summary>
        /// A loop that receives and parses link messages.
        /// </summary>
        private void ReceiveLoop()
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();

            while (!Closed)
            {
                if (Tunnel.Closed)
                {
                    Log.Error("ITunnel closed, ending ReceiveLoop");
                    Close();
                    return;
                }

                Message msg = Receive();

                if (msg == null)
                {
                    Log.Trace("Null message, continuing");
                    continue;
                }

                OnMessageReceived?.Invoke(this, msg);

                if (msg.Type == MessageType.Data)
                {
                    Tunnel.DataBytesReceived += msg.Store["data"].Length;
                    OnDataReceived?.Invoke(this, msg.Store["data"]);
                }

                if (msg.Type == MessageType.Heartbeat && !HeartbeatCapable)
                {
                    HeartbeatCapable = true;
                }
            }
        }
예제 #5
0
        public void Poll()
        {
            lock (_commandQueue)
            {
                while (_commandQueue.Count > 0)
                {
                    UdpCommand command = _commandQueue.Dequeue();
                    switch (command)
                    {
                    case UdpCommand.Connect:
                        byte[] connectionData = _dataQueue.Dequeue();
                        OnConnectionAccepted?.Invoke(connectionData);
                        break;

                    case UdpCommand.Disconnect:
                        OnDisconnect?.Invoke();
                        break;

                    case UdpCommand.Data:
                        byte[] data = _dataQueue.Dequeue();
                        OnDataReceived?.Invoke(data);
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }
                }
            }
        }
예제 #6
0
        public static string TransmitExtended(string address)
        {
            OnDataSend?.Invoke(address, null);

            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);
                request.UserAgent = AppSettings.UserAgent;
                request.Accept    = "application/json";

                WebResponse response = (HttpWebResponse)request.GetResponse();
                if (response == null)
                {
                    return(null);
                }

                Stream       stream      = response.GetResponseStream();
                StreamReader reader      = new StreamReader(stream);
                string       strResponse = reader.ReadToEnd();

                OnDataReceived?.Invoke(strResponse);

                stream.Close();
                reader.Close();
                response.Close();

                return(strResponse);
            }
            catch (Exception e)
            {
                OnDataErrorReceived?.Invoke(e.Message);
                return(null);
            }
        }
예제 #7
0
        private void OnMessageRecieved(ArraySegment <byte> data)
        {
            try
            {
                //When we recieve we need to use this
                //pending task to notify awaiters that we've actually produced
                //new data from an incoming message.
                lock (SyncObj)
                {
                    //VERY important to always call/handle this first
                    //otherwise you will encounter a race condition, or return before handling
                    //due to the return below too.
                    //Most importantly there is a race condition for the continutation if we don't
                    //have the data received first.
                    OnDataReceived?.Invoke(this, data);

                    if (PendingRecieveSource.Task.IsCompleted)
                    {
                        return;
                    }

                    PendingRecieveSource.SetResult(true);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($"Failed to handle incoming WebGL Websocket data. Reason: {e}");
                throw;
            }
        }
예제 #8
0
 private void OnLocalReceive(byte[] obj)
 {
     //接收到的数据
     LastTime = DateTime.Now;
     logger.Trace("[{0}:{1}]接收到数据: {2}", IpAddress, Port, obj.Length);
     OnDataReceived?.Invoke(obj);
 }
예제 #9
0
        async void ReadAsync()
        {
            while (TcpClient.Connected)
            {
                try
                {
                    int read = await TcpClient.GetStream().ReadAsync(buffer, bufferPos, buffer.Length - bufferPos);

                    if (read <= 0)
                    {
                        Thread.Sleep(250);
                        continue;
                    }
                    bufferPos += read;

                    if (bufferPos < 3)
                    {
                        Thread.Sleep(250);
                        continue;
                    }

                    byte[] header = new byte[4];
                    Array.Copy(buffer, 0, header, 0, 4);
                    if (BitConverter.IsLittleEndian)
                    {
                        Array.Reverse(header);
                    }
                    int len = BitConverter.ToInt32(header, 0);

                    if (len > 0 && bufferPos >= len)
                    {
                        byte[] data = new byte[len];
                        Array.Copy(buffer, 4, data, 0, len);

                        var packet = new PacketReader <TOpcode>(data);
                        if (OnDataReceived == null)
                        {
                            logger.Warn($"No handler found for opcode: {packet.Opcode}");
                        }

                        OnDataReceived?.Invoke(this, new TcpPacketEventArgs <TOpcode> {
                            TcpClient = this, Packet = packet
                        });

                        int extra = bufferPos - (len + 4);
                        Array.Copy(buffer, len + 4, buffer, 0, extra);
                        bufferPos = extra;
                    }
                }
                catch (IOException)
                {
                    if (TcpClient.Connected)
                    {
                        Thread.Sleep(125);
                    }
                }
            }
            logger.Debug($"Client {Id} disconnected");
            OnDisconnected?.Invoke(this, new TcpSocketEventArgs <TOpcode>(this));
        }
예제 #10
0
        public async Task StartAsync(CancellationToken?token = null)
        {
            _tokenSource = CancellationTokenSource.CreateLinkedTokenSource(token ?? new CancellationToken());
            _token       = _tokenSource.Token;
            _listener.Start();
            _listening = true;

            try
            {
                while (!_token.IsCancellationRequested)
                {
                    await Task.Run(async() =>
                    {
                        var tcpClientTask = _listener.AcceptTcpClientAsync();
                        var result        = await tcpClientTask;
                        OnDataReceived?.Invoke(this, new DataReceivedEventArgs(result.GetStream()));
                    }, _token);
                }
            }
            finally
            {
                _listener.Stop();
                _listening = false;
            }
        }
예제 #11
0
파일: Sender.cs 프로젝트: fr33rk/PL.Common
        /// <summary>Reads the asynchronous from the connection.
        /// </summary>
        /// <param name="stream">The socket stream.</param>
        /// <param name="buffer">The buffer to use for storing bytes.</param>
        private async void ReadAsync(NetworkStream stream, byte[] buffer)
        {
            try
            {
                var amountRead = await stream.ReadAsync(buffer, 0, buffer.Length);

                if (amountRead > 0)
                {
                    var text = Encoding.UTF8.GetString(buffer, 0, amountRead);

                    mLogFile?.Debug($"Received: {text}");

                    OnDataReceived?.Invoke(this, new SocketDataReceivedEventArgs(text));

                    // Continue reading
                    ReadAsync(stream, buffer);
                }
                else
                {
                    mLogFile?.Info("No data found. The connection seems to be closed.");
                    ResetConnection();
                }
            }
            catch (ObjectDisposedException)
            {
                // Occurs when the connection is closed.
            }
            catch (Exception e)
            {
                mLogFile?.Error(e.Message);
                ResetConnection();
            }
        }
예제 #12
0
        //should only receive END_TASK<space><CSV>
        private void Server_OnDataReceived(object sender, ServerEventArgs e)
        {
            string message = e.Message;

            //try catch because of parsing
            try
            {
                if (message.Split(' ')[0] == "END_TASK")
                {
                    //all is OK; get the data; place it as most recent


                    messages.Enqueue(message.Split(new char[] { ' ' }, 2)[1]);



                    //in the end notify anybody who might be above
                    //black bloody magic that's what this is
                    Application.Current.Dispatcher.BeginInvoke(
                        DispatcherPriority.Background,
                        new Action(() => OnDataReceived.Invoke(this, new SimulatorEventArgs("New message enqueued."))));
                }
                else
                {
                    throw new Exception("Message received from client simulator did not parse well");
                }
            }
            catch (Exception ex)
            {
            }
        }
예제 #13
0
        protected override void ReadAsync()
        {
            Byte[] Message = UDPManager.Receive(ref UDPEndpoint);
            string Line    = Encoding.ASCII.GetString(Message);

            OnDataReceived.Invoke(Line);
        }
예제 #14
0
 public static async Task StartClientSocketAsync()
 {
     try
     {
         _cancellationClientToken = CancellationTokenSource.CreateLinkedTokenSource(new CancellationToken());
         while (!_cancellationClientToken.Token.IsCancellationRequested)
         {
             await Task.Run(() =>
             {
                 if (PlayerClient.Connected && PlayerClient.GetStream().DataAvailable&&
                     PlayerClient.GetStream().CanRead)
                 {
                     NetworkStream stream = PlayerClient.GetStream();
                     byte[] data          = new byte[1024 * 1024];
                     string json          = string.Empty;
                     var bytes            = stream.Read(data, 0, data.Length);
                     if (bytes > 0)
                     {
                         json = Encoding.ASCII.GetString(data, 0, bytes);
                     }
                     OnDataReceived?.Invoke(null, new DataReceivedEvent(json));
                 }
                 Thread.Sleep(25);
             }, _cancellationClientToken.Token);
         }
     }
     catch
     {
         MessageBox.Show("Client disconnected");
     }
     finally
     {
         PlayerClient.Client.Close();
     }
 }
예제 #15
0
 private async void ListenToClientAsync(TcpClient client, CancellationToken token)
 {
     await Task.Run(() =>
     {
         try
         {
             while (client.Connected && !_token.IsCancellationRequested)
             {
                 OnDataReceived?.Invoke(client, new DataReceivedEventArgs(Name, client.GetStream(), ((IPEndPoint)client.Client.RemoteEndPoint).Address));
             }
         }
         catch (Exception e)
         {
             _Logger.Log(Name, e.ToLog("Client closed unexpectedly!"), LogLevels.Fatal);
         }
         finally
         {
             try
             {
                 client.Close();
             }
             catch (Exception e)
             {
                 _Logger.Log(Name, e.ToLog("Client closed with error!"), LogLevels.Fatal);
             }
         }
     });
 }
예제 #16
0
        //should only receive END_TASK<space><CSV>
        private void Server_OnDataReceived(object sender, ServerEventArgs e)
        {
            string message = e.Message;

            //try catch because of parsing
            try
            {
                if (message.Split(' ')[0] == "END_TASK")
                {
                    //all is OK; get the data; place it as most recent
                    messages.Enqueue(message.Split(' ')[1]);


                    //in the end notify anybody who might be above
                    OnDataReceived.Invoke(this, new SimulatorEventArgs(message));
                }
                else
                {
                    throw new Exception("Message received from client simulator did not parse well");
                }
            }
            catch (Exception ex)
            {
            }
        }
예제 #17
0
        public async Task StartAsync()
        {
            tokenSource = new CancellationTokenSource();
            tokenSource.Token.Register(() => listener.Stop());
            listener.Start();
            Listening = true;

            try
            {
                while (!tokenSource.Token.IsCancellationRequested)
                {
                    await Task.Run(async() =>
                    {
                        var result = await listener.AcceptTcpClientAsync();
                        OnDataReceived?.Invoke(result.Client, result.GetStream());
                    }, tokenSource.Token);
                }
            }
            catch (ObjectDisposedException)
            {
                // If we cancelled the token and that Stopped listener, AcceptTcpClientAsync() will throw this exception
            }
            finally
            {
                listener.Stop();
                Listening = false;
            }
        }
예제 #18
0
        /// <summary>
        /// Subscribe to a given characteristic and sets a delegate where the data will be returned whenever the server
        /// device notifies any new data
        /// </summary>
        public static void Subscribe(Characteristic characteristic, OnDataReceived onDataReceived)
        {
            CheckIfInitialized();

            if (CurrentState != State.Connected && CurrentState != State.Subscribing)
            {
                throw new Exception("You need to be connected to a device before you can subscribe to any characteristic");
            }

            SetState(State.Subscribing);
            Observable
            .Timer(TimeSpan.FromSeconds(2f))
            .Subscribe(_ =>
            {
                Debug.Log("Subscribing..");
                BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(characteristic.Device.Address,
                                                                                      characteristic.ServiceUuid, characteristic.CharacteristicUuid,
                                                                                      (__, ___) => SetState(State.Communicating),
                                                                                      (address, characteristicUuid, bytes) =>
                {
                    onDataReceived?.Invoke(new Data
                    {
                        Characteristic = characteristic,
                        RawData        = bytes
                    });
                });
            });
        }
예제 #19
0
        /// <summary>
        /// Gets the CSV file as a stream reader object.
        /// </summary>
        /// <param name="address">The URI to use</param>
        /// <returns>The response from Server</returns>
        public static StreamReader GetCsvStream(string address)
        {
            OnDataSend?.Invoke(address, null);

            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);
                request.UserAgent = AppSettings.UserAgent;
                request.Accept    = "text/csv";

                var response = (HttpWebResponse)request.GetResponse();
                if (response == null)
                {
                    return(null);
                }

                Stream       stream       = response.GetResponseStream();
                StreamReader streamReader = new StreamReader(stream);
                OnDataReceived?.Invoke(response.StatusCode.ToString());
                return(streamReader);
            }
            catch (Exception e)
            {
                OnDataErrorReceived?.Invoke(e.Message);
                return(null);
            }
        }
예제 #20
0
 private void ReceiverMethod()
 {
     try
     {
         while (oscReceiver.State != OscSocketState.Closed)
         {
             if (oscReceiver.State == OscSocketState.Connected)
             {
                 ReceiverSemaphore.WaitOne();
                 data = oscReceiver.Receive();
                 if (((OscMessage)data).Address == "/DTDT")
                 {
                     OnDataReceived?.Invoke(data);
                 }
                 ReceiverSemaphore.Release();
             }
         }
     }
     catch (Exception ex)
     {
         if (oscReceiver.State == OscSocketState.Connected)
         {
             Console.WriteLine("Exception in listen loop");
             Console.WriteLine(ex.Message);
         }
     }
 }
예제 #21
0
        public void receiveSessionData()
        {
            NetworkStream stream = client.GetStream();

            while (true)
            {
                try
                {
                    while (!stream.DataAvailable)
                    {
                        ;                          //wait while nothing is available
                    }
                }
                catch (Exception e)
                {
                    break;
                }



                Byte[] bytes = new Byte[client.Available];

                stream.Read(bytes, 0, bytes.Length);

                NewTextData = System.Text.Encoding.UTF8.GetString(bytes);

                receivedText.Add(NewTextData);


                OnDataReceived.Invoke(this, new ServerEventArgs("Received: " + NewTextData.ToString()));
            }
        }
예제 #22
0
        private void _WebSocket_OnMessage(object sender, MessageEventArgs e)
        {
            _lastReceivedTime = DateTime.UtcNow;

            if (e.IsBinary)
            {
                string data = GZipDecompresser.Decompress(e.RawData);

                var pingMessage = JsonConvert.DeserializeObject <PingMessageV1>(data);
                if (pingMessage.IsPing())
                {
                    Console.WriteLine($"Received ping:{pingMessage.ts}");
                    string pongData = $"{{\"op\":\"pong\", \"ts\":{pingMessage.ts}}}";
                    _WebSocket.Send(pongData);
                    Console.WriteLine($"Replied pong:{pingMessage.ts}");
                }
                else
                {
                    JToken json = JToken.Parse(data);
                    string op   = json.Value <string>("op");
                    if (String.Equals(op, "auth"))
                    {
                        var response = JsonConvert.DeserializeObject <WebSocketV1AuthResponse>(data);

                        OnAuthenticationReceived?.Invoke(response);
                    }
                    else
                    {
                        var response = JsonConvert.DeserializeObject <DataResponseType>(data);

                        OnDataReceived?.Invoke(response);
                    }
                }
            }
        }
예제 #23
0
        public string ExecuteWaitAndRead(string command)
        {
            var early = CurrentSp.ReadExisting();

            if (OnDataReceived != null)
            {
                OnDataReceived.Invoke(early);
            }

            var result = new StringBuilder();

            CurrentSp.WriteLine(command);
            for (var i = 0; i < MaxRetries; i++)
            {
                var s = CurrentSp.ReadExisting();
                result.Append(s);
                if (OnDataReceived != null)
                {
                    OnDataReceived.Invoke(s);
                }
                if (_end.IsMatch(
                        result.ToString()))
                {
                    break;
                }
                Thread.Sleep(50);
            }
            var str = result.ToString();

            return(str.Substring(command.Length + 2, str.Length - 4 - command.Length)); // Kill the echo, '\r\n> '
        }
예제 #24
0
        public void Receive()
        {
            if (!Connected)
            {
                return;
            }

            m_socket.BeginReceive(m_buffer, 0, m_buffer.Length, SocketFlags.None, out var outBeginError, iar =>
            {
                if (!Connected)
                {
                    return;
                }

                int size = m_socket.EndReceive(iar, out var outEndError);

                if (size == 0 || outEndError != SocketError.Success)
                {
                    Dispose();
                }
                else
                {
                    OnDataReceived?.Invoke(m_buffer, size);
                }
            }, null);

            if (outBeginError != SocketError.Success)
            {
                Dispose();
            }
        }
예제 #25
0
        private void _WebSocket_OnMessage(object sender, MessageEventArgs e)
        {
            _lastReceivedTime = DateTime.UtcNow;

            if (e.IsBinary)
            {
                string data = GZipDecompresser.Decompress(e.RawData);

                var pingMessage = JsonConvert.DeserializeObject <PingMessageV1>(data);
                if (pingMessage.IsPing())
                {
                    AppLogger.Trace($"WebSocket received data, ping={pingMessage.ts}");
                    string pongData = $"{{\"op\":\"pong\", \"ts\":{pingMessage.ts}}}";
                    _WebSocket.Send(pongData);
                    AppLogger.Trace($"WebSocket repied data, pong={pingMessage.ts}");
                }
                else
                {
                    dynamic json = JToken.Parse(data);
                    string  op   = json.op;
                    if (String.Equals(op, "auth"))
                    {
                        var response = JsonConvert.DeserializeObject <WebSocketV1AuthResponse>(data);

                        OnAuthenticationReceived?.Invoke(response);
                    }
                    else
                    {
                        var response = JsonConvert.DeserializeObject <DataResponseType>(data);

                        OnDataReceived?.Invoke(response);
                    }
                }
            }
        }
예제 #26
0
        private void ListenLoop()
        {
            int bytesRead;

            while (!_IsStopped)
            {
                byte[] buffer = new byte[258];
                bytesRead = 0;

                try
                {
                    bytesRead = _ClientStream.Read(buffer, 0, 258);
                }
                catch
                {
                    break;
                }

                if (bytesRead == 0)
                {
                    Thread.Sleep(15);
                    continue;
                }

                var message = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                OnDataReceived?.Invoke(message);

                Thread.Sleep(15);
            }
        }
예제 #27
0
        public async Task StartAsync(CancellationToken?token = null)
        {
            _tokenSource = CancellationTokenSource.CreateLinkedTokenSource(token ?? new CancellationToken());
            _token       = _tokenSource.Token;
            _listener.Start();
            _listening = true;

            try
            {
                try
                {
                    while (!_token.IsCancellationRequested)
                    {
                        await Task.Run(async() =>
                        {
                            var tcpClientTask = _listener.AcceptTcpClientAsync().WithWaitCancellation(_token);
                            var result        = await tcpClientTask;
                            var ipAddressStr  = result.Client.RemoteEndPoint.ToString();

                            OnDataReceived?.Invoke(this, new DataReceivedEventArgs(result.GetStream(), ipAddressStr, DateTime.Now));
                        }, _token);
                    }
                } catch (OperationCanceledException ex) { }
            }
            finally
            {
                _listener.Stop();
                _listening = false;
            }
        }
예제 #28
0
 //---------------------------------------------------------------------
 void _raiseDataReceived(byte[] data, int len)
 {
     if (OnDataReceived != null)
     {
         OnDataReceived.Invoke(data, len);
     }
 }
예제 #29
0
        async void ReceiveAsync()
        {
            while (running)
            {
                try
                {
                    var result = await UdpClient.ReceiveAsync();

                    var packet = new PacketReader <TOpcode>(result.Buffer);

                    if (OnDataReceived == null)
                    {
                        logger.Warn($"No handler found for opcode: {packet.Opcode}");
                    }

                    OnDataReceived?.Invoke(this, new AsyncUdpPacketEventArgs <TOpcode>
                    {
                        Client = this,
                        Packet = packet,
                        Sender = result.RemoteEndPoint
                    });
                }
                catch (SocketException e)
                {
                    running = false;
                    logger.Debug(e);
                }
            }
            logger.Debug($"Client {Id} disconnected");
            OnDisconnected?.Invoke(this, new AsyncUdpSocketEventArgs <TOpcode> {
                Client = this
            });
        }
예제 #30
0
파일: Comms.cs 프로젝트: AlanWills/Net
        /// <summary>
        /// Callback which processes a message sent from the server
        /// </summary>
        /// <param name="ar"></param>
        private void StreamReceived(IAsyncResult ar)
        {
            int bytesRead = 0;

            try
            {
                lock (Client.GetStream())
                {
                    bytesRead = Client.GetStream().EndRead(ar);
                }
            }
            catch { }

            //Create the byte array with the number of bytes read
            byte[] data = new byte[bytesRead];

            //Populate the array
            for (int i = 0; i < bytesRead; i++)
            {
                data[i] = ReadBuffer[i];
            }

            OnDataReceived?.Invoke(data);

            //Listen for new data
            StartListening();
        }