我有来自W& T的COM-Server ++的Socket连接,它连接到互联网,并通过串口转USB连接到我的电脑。
用于TCP出站通信的COM-Server的设置为:
启动。数据包选项:禁用
无效。超时:00030
连接。超时:00300
断开字符:000
客户: “C”+地址:禁用
响应模式:禁用
在我的应用程序中,我读取了这个服务器的传入数据:
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的read方法有错误的工作流程?
答案 0 :(得分:4)
一个简单的解决方案如下:
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>
。
答案 1 :(得分:0)
我并不完全了解这个图书馆。但是一个流返回它得到的东西,没有人确保它实际上是全部... 这可能会解决您的问题:How to read all of Inputstream in Server Socket JAVA
编辑:您也可以尝试使用ObjectInputStream(如果可能)将String作为Object。