我有一个从W&T到COM-Server ++的套接字连接,它连接到互联网,也通过串行到USB连接到我的PC。
用于TCP出站通信的COM-Server设置为:
主动行动。数据包选项:禁用无活动。超时时间: 00030 连接。超时时间: 00300 断开Char : 000 客户端:"C"+Addr :禁用 响应模式:禁用
在我的应用程序中,我读取此服务器的传入数据如下:
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读取方法的工作流错误?
发布于 2017-02-24 10:41:20
一个简单的解决方案如下所示:
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>。
发布于 2017-02-24 09:52:12
我不太了解这个图书馆。但是流返回它得到的,没有人保证它实际上是所有的.这可能解决您的问题:如何在服务器套接字JAVA中读取所有Inputstream
编辑:您还可以尝试使用ObjectInputStream (如果可能的话)将字符串作为对象。
https://stackoverflow.com/questions/42435408
复制相似问题