1
我正在開發一個串行端口應用程序。而且我無法正確接收數據。我使用ReadExisting()來讀取即將到來的數據。 .NET串行端口 - 接收丟失的數據
這是我的代碼。請指教,接收數據的正確方法是什麼,以及如果我想檢查每條消息的長度和格式的有效性,該怎麼辦。
public void serialport_connect(String port, int baudrate, Parity parity, int databits, StopBits stopbits)
{
DateTime dt = DateTime.Now;
String dtn = dt.ToShortTimeString();
sport = new System.IO.Ports.SerialPort(port, baudrate, parity, databits, stopbits);
try
{
sport.Open();
status.AppendText("[" + dtn + "] " + "Connected\n");
sport.DataReceived += new SerialDataReceivedEventHandler(sport_DataReceived);
}
catch (Exception ex) { MessageBox.Show(ex.ToString(), "Error"); }
}
private void sport_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
DateTime dt = DateTime.Now;
String dtn = dt.ToShortTimeString();
String comingData = sport.ReadExisting();
if (comingData != String.Empty)
{
Dispatcher.Invoke(new Action(() =>
{
current.AppendText("[" + dtn + "] " + "Received: " + sport.ReadExisting() + "\n");
}));
}
}
謝謝。