Home > Net > A serial port should adopt what method receives a message?
A serial port should adopt what method receives a message?
Time:10-28
Using the SerialPort class receives a serial port communication message, message format is 0 xf3 xx xx xx,,, xx xx 0 XFD, the header is the F3, the tail is FD, xx is data, message length is not fixed, interval between two adjacent message about 500 milliseconds, consider the following several ways of judgment of message, but didn't succeed: 1, one of the most common method, set the port attribute. ReceivedBytesThreshold, after receiving a set number of bytes of data receive events triggered port. The method DataReceived, because the message length is not fixed, so I can't use this method, Port 2, use the read method. ReadTo (Encoding. The ASCII. Get string (new byte [1] XFD {0})), when read newspaper tail, stop debugging found that could not read the data, to estimate the reason is the ASCII value of 0 XFD corresponding not a printable characters, 3, the feeling is the most reasonable method should be: when a serial port for some time, for example 100 ms, not received the data, all data is read buffer, and determine the header to tail, but this kind of method how to write code? SerialPort ReadTimeout doesn't seem right, is to open a 100 ms timer? 4, because a message between two adjacent bytes of data, the time interval is almost equal to zero, so each receive a byte to read and judge once, this way too late time,
Which method should be used? Directly, thanks!
CodePudding user response:
Unlimited listening to receive this is for you, will receive the data in a queue, then the asynchronous extraction fragments from the queue,