private void ReceiveLoop() { try { byte[] array = new byte[1024]; //1KByte buffer while (_socket != null && _socket.Connected) { int available = _socket.Available; if (available > 0) { int count = _socket.Receive(array); string dataReceived = Encoding.UTF8.GetString(array, 0, count); OnReceiveString?.Invoke(this, new LISConnectionReceivedDataEventArgs(dataReceived)); } else { Thread.Sleep(5); //sleep 5 ms } } } catch (SocketException ex) when(ex.ErrorCode == 10057) { // Log the exception and exit to stop receiving. _logger.Error(ex.Message); } }
public async Task StartListeningAsync() { await Task.Run(() => { _isInServerMode = true; TcpListener server = new TcpListener(IPAddress.Parse(NetWorkAddress), NetWorkPort); server.Start(); byte[] bytes = new Byte[1024]; string data = null; while (true) { _client = server.AcceptTcpClient(); _socket = _client.Client; data = null; NetworkStream stream = _client.GetStream(); for (int i = stream.Read(bytes, 0, bytes.Length); i != 0; i = stream.Read(bytes, 0, bytes.Length)) { data = Encoding.UTF8.GetString(bytes, 0, i); OnReceiveString?.Invoke(this, new LISConnectionReceivedDataEventArgs(data)); } _client.Close(); } }); }