-4

晚上好。有一个套接字连接。来自服务器的消息是 8 个字节。在建立连接之前,如何将它们作为无穷无尽的流读入?客户端部分是用 Java 编写的。

4

1 回答 1

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;
    }
}
于 2013-08-13T18:53:30.650 回答