什么Socket.getInputStream()。read()方法会在java中做什么?

时间:2011-08-05 14:54:44

标签: java sockets

我有这样的代码:

class ConnectionHandler implements Runnable {

private Socket socket;
private InputStream is;
private OutputStream os;
private  Packetizer packetizer;
boolean closed = true;

public ConnectionHandler(Socket socket, ProtocolHandler ph) {
    this.socket = socket;
    try {
        is = socket.getInputStream();
        os = socket.getOutputStream();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
Thread t = new Thread(this);
    t.start();
    //log.debug("ConnectionHandler const done");
}

public void run() {
    try
    {
        //
        // Read a message sent by client application
        //

        closed = false;
        while (!closed)
        {
            if (is.available() > 0) 
            {
                byte c = (byte) (0xff & is.read());
                //log.debug("r " + c);

            } else {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    //e.printStackTrace();
                }
            }
        }

        is.close();
        os.close();
        socket.close();

    } catch (IOException e) {
    }
}

我的问题是这是什么用途 - > byte c =(byte)(0xff& is.read());

请让我知道你的想法。

请帮帮我。提前谢谢。

1 个答案:

答案 0 :(得分:4)

它将从套接字读取单个字节的数据。 0xff & ...部分在这里是不必要的(或实际上是一个坏主意),因为InputStream.read只返回0-255范围内的值,除非它实际到达数据的末尾,在这种情况下它返回-1

(通常0xff & ...用于将签名的byte值转换为无符号int值。此处输入int结果byte变量,但......)