我有一个到 COM-Server ++ 的套接字连接来自 W&T,已连接到互联网并通过串口转 USB 连接到我的 PC。
用于 TCP 出站通信的 COM-Server 设置为:
Activ. Packet Options : disabled
Inactiv. Timeout : 00030
Connect. Timeout : 00300
Disconnect Char : 000
Client: "C"+Addr : disabled
Response Mode : disabled
在我的应用程序中,我像这样读取此服务器的传入数据:
boolean running = true;
log.info( "{0}: Starting to listen for input data", name );
while ( running )
{
try
{
int charsRead = inputStream.read( buffer );
if ( charsRead < 0 )
{
running = false;
}
else
{
byte[] received = Arrays.copyOf( buffer, charsRead );
/** TODO: Call interface of protocol here */
log.info( "{0}: data received: {1}", connection.getName(), new String( received ) );
}
}
catch ( IOException ie )
{
setStatus( ConnectionStatus.FAILURE );
close();
/** TODO: Exception handling */
running = false;
}
}
如果我发送:test<CR><LF>
从设备我得到的日志输出是:
(terminal1) terminal1: data received: t
(terminal1) terminal1: data received: e
(terminal1) terminal1: data received: st
(terminal1) terminal1: data received:
(terminal1) terminal1: data received:
然而,所需的输出是:
(terminal1) terminal1: data received: test
我的错误在哪里,或者我假设了 InputStream 的读取方法的错误工作流?
最佳答案
一个简单的解决方案如下所示:
StringBuilder sb = new StringBuilder();
int c;
while ( (( c = inputStream.read() ) >= 0) && (c != 0x0a /* <LF> */) ) {
if ( c != 0x0d /* <CR> */ ) {
sb.append( (char)c );
} else {
// Ignore <CR>.
}
}
return sb.toString();
此代码一直读取字节,直到找到行尾(或流尾),由 <LF>
发出信号.
我们期待<CR><LF>
其中 <CR>
是行分隔符的一部分,所以我们忽略任何 <CR>
同时收集所有其他字节。
关于java - 从套接字的 InputStream 读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42435408/