晚上好。有一个套接字连接。来自服务器的消息是8个字节。在有连接之前,我如何将它们作为一个无休止的流程阅读?客户端部分是用Java编写的。
答案 0 :(得分:0)
要从套接字读取8个字节,直到服务器关闭套接字,请使用与此类似的内容:
void readSocket(Socket socket)
{
try
{
byte[] data = new byte[8];
int ret;
while (true)
{
int offset=0;
// keep reading until we got 8 bytes
while (offset < data.length)
{
// when read returns 0 means the socket is closed.
// if return < 0 there is an error in both cases we must quit.
if ((ret = socket.getInputStream().read(data, offset, data.length-offset)) <= 0) return;
offset+=ret;
}
// We got 8 bytes, process them
// ... and loop for next packet
}
}
catch (Exception e)
{
e.printStackTrace();
// there is an error in the socket, quit.
return;
}
}