23.07.2013 Views

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

}<br />

}<br />

}<br />

// This next line is problematic on non-ASCII systems<br />

byte[] b = request.getBytes();<br />

OutputStream out = s.getOutputStream();<br />

InputStream in = s.getInputStream();<br />

out.write(b);<br />

out.flush();<br />

StreamCopier.copy(in, System.out);<br />

in.close();<br />

out.close();<br />

s.close();<br />

}<br />

catch (MalformedURLException e) {System.err.println(e);}<br />

catch (<strong>IO</strong>Exception e) {System.err.println(e);}<br />

<strong>Java</strong> I/O<br />

For example, when SocketTyper connects to http://www.oreilly.com/, here is what you see:<br />

% java SocketTyper http://www.oreilly.com/<br />

HTTP/1.0 200 OK<br />

Server: WN/1.15.1<br />

Date: Sun, 09 Aug 1998 20:05:03 GMT<br />

Last-modified: Fri, 07 Aug 1998 23:44:36 GMT<br />

Content-type: text/html<br />

Title: www.oreilly.com -- Welcome to O'Reilly & Associates!<br />

Link: ; rev="Made"<br />

<br />

<br />

<br />

Notice the header lines you didn't see in Example 5.1. When you use the URL class to<br />

download a web page, the associated protocol handler never shows you the HTTP header.<br />

5.4 Server Sockets<br />

There are two ends to each connection: the client, which initiates the connection, and the<br />

server, which responds to the connection. So far, we've only discussed the client side and<br />

assumed that a server existed out there for the client to talk to. To implement a server, you<br />

need to write a program that waits for other hosts to connect to it. A server socket binds to a<br />

particular port on the local machine (the server); once it has successfully bound to a port, it<br />

listens for incoming connection attempts from remote machines (the clients). When the server<br />

detects a connection attempt, it accepts the connection. This creates a socket between the two<br />

machines over which the client and the server communicate.<br />

Many clients can connect to a port on the server simultaneously. Incoming data is<br />

distinguished by the port to which it is addressed and the client host and port from which it<br />

came. The server can tell for which service (like HTTP or FTP) the data is intended by<br />

68

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!