2011-08-05 71 views
0

我有這樣的代碼:什麼Socket.getInputStream()。read()方法會在java中做什麼?

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) { 
    } 
} 

我的問題是什麼用的這 - >字節C =(字節)(0xFF的& is.read());

請讓我知道您的想法。

請幫我一把。提前致謝。

回答

4

它將從套接字讀取一個字節的數據。由於InputStream.read只會返回0-255範圍內的值,除非實際到達數據末尾,否則返回-1,因此0xff & ...部分在此處不必要(或實際上是一個壞主意)。

(通常0xff & ...用於將簽署byte值轉換成一個無符號int值這裏輸入int結果是可變byte雖然...)。

+0

謝謝喬恩: ) –