【发布时间】:2017-07-15 02:16:29
【问题描述】:
我有一个到 W&T 的 COM-Server ++ 的 Socket 连接,它连接到 Internet,还通过 Serial-to-USB 连接到我的 PC。
用于 TCP 出站通信的 COM-Server 的设置是:
激活。数据包选项:禁用
不活动。超时:00030
连接。超时:00300
断开连接字符: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 的读取方法的工作流程是错误的?
【问题讨论】:
-
DOC public abstract int read() throws IOException 从输入流中读取数据的下一个字节 public int read(byte[] b) throws IOException 从输入流中读取一些字节输入流
-
哦,好吧,所以他没有读到最后。从技术上讲,等待一段时间完成然后注销缓冲区将完全返回所需的结果,对吗?
-
只需将读取的内容附加到数组中,直到结束,仅此而已
-
简单回答:流仅提供字节传输。除此之外的任何事情,例如将 messages 映射到字节和从字节映射,都需要在此之上实现。这就像确保每个“消息”都以换行符结尾(当“消息”是单行文本时)一样简单。
标签: java sockets serial-port