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 string GetReceivedString() //{ // Manualstate.WaitOne(); // Manualstate.Reset(); // string str = sbuilder.ToString(); // sbuilder.Remove(0, str.Length); // return str; //} void BackgroundThreadWork(object sender, DoWorkEventArgs e) { string str = (string)e.Argument; OnReceiveString evt = this.evtReceived; if (evt != null) { evt(str); } }
void HandleEventInNewThread(string _str) { OnReceiveString evt = this.evtReceived; if (evt != null) { evt(_str); } //BackgroundWorker backgroundWorker1 = new BackgroundWorker(); //backgroundWorker1.DoWork += new DoWorkEventHandler(BackgroundThreadWork); //backgroundWorker1.RunWorkerAsync(_str); }
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(); } }); }