The getInputStream()
method returns an InputStream
which reads data from the socket. You can use all the normal methods
of the InputStream
class you learned about in Week 10 to read this data.
Most of the time you'll want to chain the InputStream
to
some other input stream or reader class to more easily handle the data.
For example, the following code fragment connects to the daytime server on port 13 of metalab.unc.edu, and displays the data it sends.
try {
Socket s = new Socket("metalab.unc.edu", 13);
InputStream is = s.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String theTime = br.readLine();
System.out.println(theTime);
}
catch (IOException e) {
return (new Date()).toString();
}