public int Read(ref byte[] outBytes, int timeOut) { try { int rxIndex = 0; outBytes.Initialize(); if (!_port.IsOpen) { PortClosed?.Invoke(); return(-1); } while (true) { Thread.Sleep(timeOut); var rxCount = _port.BytesToRead; if (rxCount < 1) { break; } _port.Read(outBytes, rxIndex, rxCount); rxIndex += rxCount; } return(rxIndex); } catch { return(-1); } }
public int Read(ref byte[] outBuffer, int bufferSize, ref int startIndex, ref int endIndex) { try { startIndex = endIndex; if (!_port.IsOpen) { PortClosed?.Invoke(); return(-1); } var rxCount = _port.BytesToRead; var tempBuffer = new byte[rxCount]; if (rxCount > 0) { _port.Read(tempBuffer, 0, rxCount); for (int i = 0; i < rxCount; i++) { outBuffer[endIndex] = tempBuffer[i]; if (++endIndex >= bufferSize) { endIndex -= bufferSize; } } } return(rxCount); } catch { return(-1); } }
private bool TestPort(IPAddress address, int port) { try { using (var client = new TcpClient()) { var result = client.BeginConnect(address, port, null, null); var success = result.AsyncWaitHandle.WaitOne(Timeout); if (!success) { PortClosed?.Invoke(this, address, port); return(false); } else { PortOpened?.Invoke(this, address, port); } client.EndConnect(result); } } catch { return(false); } return(true); }
public bool Write(string text) { try { if (!_port.IsOpen) { PortClosed?.Invoke(); return(false); } _port.Write(text); return(true); } catch { return(false); } }
public void Close() { port.Close(); PortClosed?.Invoke(); }