what Socket.getInputStream().read() method will do in java?
I have a code like this:
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) {
}
}
My question is what is the use of this -> byte c = (byte) (0xff & is.read());
Please let me know your thoughts.
Please help me out. Thanks in advance.
It will read a single byte of data from the socket. The 0xff & ...
part is unnecessary here (or actually a bad idea), as InputStream.read
will only return a value in the range 0-255, unless it's actually reached the end of the data in which case it returns -1.
(Usually 0xff & ...
is used to convert a signed byte
value into an unsigned int
value. Here the input is an int
and the result is a byte
variable though...)
精彩评论