View RSS Feed

Java Socket

Reading from a Socket

Rate this Entry
by , 04-25-2012 at 10:29 PM (801 Views)
Obtain InputStream for reading from Java Socket. This is done as following:
Java Code:
Socket socket = new Socket("jenkov.com", 80);
InputStream in = socket.getInputStream();

int data = in.read();
//... read more data...

in.close();
socket.close();
Pretty simple, right?

This shall be noticed that one canít read always from the InputStream of Socket till -1 is returned, as it could be done while a file is read. Reason behind this thing is that -1 just return as the connections are closed by sever. However, connection might not be always closed by the server. Might be, one wants to send many requests at the similar connections. In such particular case, it would be stupidity to close connections.

Submit "Reading from a Socket" to Facebook Submit "Reading from a Socket" to Digg Submit "Reading from a Socket" to del.icio.us Submit "Reading from a Socket" to StumbleUpon Submit "Reading from a Socket" to Google

Categories
Tutorial

Comments