Ejemplo n.º 1
0
        public async void StartUDPReceiver()
        {
            while (IsUDPReading)
            {
                IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, Port);
                UdpClient  Client        = new UdpClient(localEndPoint);

                FnOnMessage("Waiting for UDP connection...");
                try {
                    FnOnMessage("Reading from UDP Connection...");
                    while (IsUDPReading)
                    {
                        UdpReceiveResult result = await Client.ReceiveAsync();

                        int bytesRead = result.Buffer.Length;
                        if (bytesRead > 0)
                        {
                            //Add data to received buffer
                            OnDataReceive?.Invoke(this, result.Buffer);
                            //FnOnMessage($"Reading data of {bytesRead} bytes from Server...");
                            WriteTo(result.Buffer);
                        }
                        await Task.Delay(10);
                    }
                } catch (Exception ex) {
                    FnOnMessage(ex.Message);
                }
                Client.Close();
                FnOnMessage("... Disconnected.");
                await Task.Delay(50000);
            }
        }
Ejemplo n.º 2
0
 public void ShowDiagnosticInfo(string message)
 {
     if (_showDiagnosticInfo)
     {
         OnDataReceive?.Invoke(message);
     }
 }
Ejemplo n.º 3
0
        public void ReadCallback(IAsyncResult ar)
        {
            String content = String.Empty;

            // Retrieve the state object and the handler socket
            // from the asynchronous state object.
            StateObject state   = (StateObject)ar.AsyncState;
            Socket      handler = state.workSocket;

            try {
                // Read data from the client socket.
                int bytesRead = handler.EndReceive(ar);

                if (bytesRead > 0)
                {
                    //Add data to received buffer
                    byte[] buffer = state.buffer.Take(bytesRead).ToArray();
                    OnDataReceive?.Invoke(this, buffer);

                    //FnOnMessage($"Reading data of {bytesRead} bytes from Server...");
                    WriteTo(buffer);

                    // Not all data received. Get more.
                    handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
                }
                else
                {
                    FnOnMessage($"Closing the client connection...");
                    handler.Shutdown(SocketShutdown.Receive);
                    handler.BeginDisconnect(true, new AsyncCallback(DisconnectCallback), state);
                }
            } catch (Exception ex) {
                FnOnMessage(ex.Message, ex);
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// 端口独立线程,crtsnt数组序号
        /// </summary>
        void ClientThread(object clienttable)
        {
            var table = (ClientItem)clienttable;

            try
            {
                table.WorkEnable = true;
                table.Remote     = IPAddress.Parse(table.Client.Client.RemoteEndPoint.ToString().Split(':')[0]);
                OnAccept?.Invoke(table.Remote);
                using (var ns = table.Client.GetStream())
                {
                    var buffer = new byte[BufferSize];
                    var read   = 0;
                    while (table.WorkEnable && table.Client.Connected)
                    {
                        using (var ms = new MemoryStream())
                        {
                            while (ns.DataAvailable)//!sr.EndOfStream)
                            {
                                read = ns.Read(buffer, 0, BufferSize);
                                ms.Write(buffer, 0, read);
                            }
                            OnDataReceive?.Invoke(table.Remote, ms.ToArray());
                        }
                        Thread.Sleep(Interval);
                    }
                }
            }
            finally
            {
                table.Client.Close();
                ClientTable.Remove(table);
                OnDisConnect?.Invoke(table.Remote);
            }
        }
Ejemplo n.º 5
0
        private void ListeningCliente(CancellationToken cancel)
        {
            _tcpClient = AcceptTcpClient();
            NetworkStream network = _tcpClient.GetStream();

            while (!cancel.IsCancellationRequested && _tcpClient.Connected)
            {
                try
                {
                    var listBytes = new List <byte>();

                    int read = network.ReadByte();
                    listBytes.Add((byte)read);
                    if (read == 'S')
                    {
                        do
                        {
                            listBytes.Add((byte)network.ReadByte());
                        }while (listBytes.Count < 2 || (listBytes.Count >= 2 && listBytes[listBytes.Count - 2] != 'C' && listBytes[listBytes.Count - 2] != 'R'));
                    }

                    OnDataReceive?.Invoke(this, listBytes.ToArray());
                }
                catch (Exception e)
                {
                    _tcpClient = null;
                    OnError?.Invoke(this, e.ToString());
                }
            }

            if (!cancel.IsCancellationRequested && !_tcpClient.Connected)
            {
                ListeningCliente(cancel);
            }
        }
Ejemplo n.º 6
0
        private void OnArrayMessage(string msg)
        {
            var parsed = BitfinexJsonSerializer.Deserialize <JArray>(msg);

            if (parsed.Count < 2)
            {
                Console.WriteLine("Invalid message format, too low items");
                return;
            }

            OnDataReceive?.Invoke(parsed);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Callback for BeginReceive method.
        /// </summary>
        /// <param name="ar">The async result.</param>
        private void ReceiveCallback(IAsyncResult ar)
        {
            var clientState = (ClientState)ar.AsyncState;

            clientState.Socket.EndReceive(ar);

            var clientBuffer = Encoding.UTF8.GetString(clientState.Buffer);

            var lines = ParseClientBuffer(clientBuffer);

            foreach (var line in lines)
            {
                OnDataReceive?.Invoke(this, new DataReceivedEventArgs(line));
            }

            clientState.Socket.BeginReceive(clientState.Buffer, 0, ClientState.BufferSize, 0, ReceiveCallback, clientState);
        }
Ejemplo n.º 8
0
 private void AsynReceiveData(IAsyncResult iAsyncResult)
 {
     try
     {
         byte[] buff = iAsyncResult.AsyncState as byte[];
         if (null != buff)
         {
             string context = Encoding.UTF8.GetString(buff);
             OnDataReceive?.Invoke(context);
         }
         buff = new byte[1024 * 4];
         networkStream.BeginRead(buff, 0, buff.Length, new AsyncCallback(AsynReceiveData), buff);
     }
     catch (Exception ex)
     {
         OnError?.Invoke(ex);
     }
 }
Ejemplo n.º 9
0
    /// <summary>
    /// 处理接收结果
    /// </summary>
    /// <param name="e"></param>
    private void processReceive(SocketAsyncEventArgs e)
    {
        if (e.SocketError == SocketError.Success && e.BytesTransferred > 0)
        {
            byte[] data = new byte[e.BytesTransferred];
            Array.Copy(e.Buffer, e.Offset, data, 0, e.BytesTransferred);
            lock (receiveBuffer)
            {
                receiveBuffer.AddRange(data);
            }
            //当缓存区数据大于4
            do
            {
                //读取前4个字节是包体的长度
                byte[] lengthBytes = receiveBuffer.GetRange(0, 4).ToArray();
                int    dataLength  = BitConverter.ToInt32(lengthBytes, 0);

                //判断缓存区剩余数据是否足够完整包体
                if (dataLength <= receiveBuffer.Count - 4)
                {
                    byte[] rev = receiveBuffer.GetRange(4, dataLength).ToArray();
                    receiveBuffer.RemoveRange(0, dataLength + 4);
                    //交到前端处理数据
                    DataReceiveEvent?.Invoke(rev);
                }
                else
                {
                    break;
                }
            } while (receiveBuffer.Count > 4);
            //是否挂起状态
            if (!client.ReceiveAsync(e))
            {
                processReceive(e);
            }
        }
        else
        {
            ProcessError(e);
        }
    }
Ejemplo n.º 10
0
 void ReadThread(ClientItem ct)
 {
     using (var ns = ct.Client.GetStream())
     {
         var buffer = new byte[BufferSize];
         var read   = 0;
         while (ct.WorkEnable && ct.Client.Connected)
         {
             using (var ms = new MemoryStream())
             {
                 while (ns.DataAvailable)
                 {
                     read = ns.Read(buffer, 0, BufferSize);
                     ms.Write(buffer, 0, read);
                 }
                 OnDataReceive?.Invoke(ct.Target.Address, ms.ToArray());
             }
             Thread.Sleep(Interval);
         }
     }
     ct.Client.Close();
     ControlTable.Remove(ct);
     OnDisconnect?.Invoke(ct.Target.Address);
 }
Ejemplo n.º 11
0
 /// <summary>
 /// Function used to fire the OnDataReceive event
 /// </summary>
 /// <param name="message">received message</param>
 protected internal void FireOnDataReceiveEvent(Message message) => OnDataReceive?.Invoke(this, message);