使用相同打开的端口读取/写入SerialPort [英] SerialPort read/write using same opened port
问题描述
我正在尝试使用SerialPort对象来侦听传入的数据并发送传出的数据.
彼此分开进行,效果很好-我可以毫无问题地发送或接收消息.当我想使此端口可用于两种操作时,就会发生问题.
我要做的是(在专用线程中):
private void SerialCommunicationsListen(SerialPort serialPort)
{
而(true)
{
字符串val = serialPort.ReadLine();
//用val
做一些代码
}
}
这是听众.我正在做的第二件事是发送数据:
公共无效SendMessage(SerialPort端口,字符串消息)
{
port.Write(message);
}
两者都使用相同的SerialPort对象.问题是,如果在侦听器打开时调用"SendMessage",则侦听器将接收数据而不是设备,如果侦听器关闭,则设备将接收数据.
我在这里做错了什么?我想同时在同一端口上从设备进行发送和接收.
I am trying to use SerialPort object to listen for incoming data and send outgoing data.
Doing each other separately, it is working well - I can send or receive with no issues. The problem happens when I want to make this port available for both operations.
What I do is this (In a dedicated thread):
private void SerialCommunicationsListen(SerialPort serialPort)
{
while (true)
{
string val = serialPort.ReadLine();
// do some code with val
}
}
This is the listener. 2nd thing I''m doing is this for sending data out:
public void SendMessage(SerialPort port, string message)
{
port.Write(message);
}
Both are using the same SerialPort object. The thing is that if I call "SendMessage" when the listener is up, the listener receives the data instead of the device, and if it is down, the device is the one receiving it.
What am I doing wrong here? I want to do both transmit and receive from the device on the same port.
推荐答案
Don''t.
问题可能是ReadLine是一个阻塞操作-直到串行端口接收到完整的行以及行结束符后,它才会返回-因此您的代码在发生这种情况之前无法执行任何其他操作.
而是使用 SerialPort.DataReceived事件 [ ^ ]并将数据自己缓存在stringbuilder yuntiul中,这样您就可以找到完整的一行.然后,您可以处理生产线.
这样一来,您的代码就不会一直坐在等待数据的位置,而无所事事!
Don''t.
The problem is probably that ReadLine is a blocking operation - it doesn''t return until a complete line together with line end character(s) has been received by the serial port - so your code can''t do anything else until that happens.
Instead, use the SerialPort.DataReceived event[^] and buffer up the data yourself in a stringbuilder yuntiul you have a complete line. You can then process the line.
That way, your code isn''t sitting waiting for data all the time and doing nothing else!
这篇关于使用相同打开的端口读取/写入SerialPort的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!