Java Reference
In-Depth Information
String hostname = "www.example.com" ;
int port = 80 ;
String filename = "/index.html" ;
g
d O
e
try ( Socket sock = new Socket ( hostname , port );
BufferedReader from = new BufferedReader (
new InputStreamReader ( sock . getInputStream ()));
PrintWriter to = new PrintWriter (
new OutputStreamWriter ( sock . getOutputStream ())); ) {
// The HTTP protocol
to . print ( "GET " + filename +
" HTTP/1.1\r\nHost: " + hostname + "\r\n\r\n" );
to . flush ();
for ( String l = null ; ( l = from . readLine ()) != null ; )
System . out . println ( l );
}
On the server side, we'll need to receive possibly multiple incoming connections. To
handle this, we'll need to kick off a main server loop, then use accept() to take a
new connection from the operating system. The new connection then will need to
be quickly passed to a separate handler class, so that the main server loop can get
back to listening for new connections. The code for this is a bit more involved than
the client case:
// Handler class
private static class HttpHandler implements Runnable {
private final Socket sock ;
HttpHandler ( Socket client ) { this . sock = client ; }
public void run () {
try ( BufferedReader in =
new BufferedReader (
new InputStreamReader ( sock . getInputStream ()));
PrintWriter out =
new PrintWriter (
new OutputStreamWriter ( sock . getOutputStream ())); ) {
out . print ( "HTTP/1.0 200\r\nContent-Type: text/plain\r\n\r\n" );
String line ;
while (( line = in . readLine ()) != null ) {
if ( line . length () == 0 ) break ;
out . println ( line );
}
} catch ( Exception e ) {
// Handle exception
}
}
}
// Main server loop
Search WWH ::




Custom Search