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.

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

That's pretty much all there is, except for a few methods dealing with socket options and some<br />

other details. In particular, there aren't methods for getting input and output streams. Instead,<br />

accept()returns a Socket object: you call the Socket's getInputStream() or<br />

getOutputStream() method. For example:<br />

try {<br />

ServerSocket ss = new ServerSocket(2345);<br />

Socket s = ss.accept();<br />

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

// Send data to the client.<br />

s.close();<br />

}<br />

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

Notice in this example, I closed the Socket s, not the ServerSocket ss. ss is still bound to<br />

port 2345. You get a new socket for each connection and reuse the server socket. For<br />

example, the next code fragment repeatedly accepts connections:<br />

try {<br />

ServerSocket ss = new ServerSocket(2345);<br />

while (true) {<br />

Socket s = ss.accept();<br />

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

// send data to the client<br />

s.close();<br />

}<br />

}<br />

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

The program in Example 5.5 reads a port number from the command line. It listens on that<br />

port for incoming connections. When it detects one, it answers back with the client's address<br />

and port and its own. Then it closes the connection.<br />

Example 5.5. The HelloServer Program<br />

import java.net.*;<br />

import java.io.*;<br />

public class HelloServer {<br />

public final static int defaultPort = 2345;<br />

public static void main(String[] args) {<br />

int port = defaultPort;<br />

try {<br />

port = Integer.parseInt(args[0]);<br />

}<br />

catch (Exception e) {}<br />

if (port = 65536) port = defaultPort;<br />

try {<br />

ServerSocket ss = new ServerSocket(port);<br />

while (true) {<br />

try {<br />

Socket s = ss.accept();<br />

70

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

Saved successfully!

Ooh no, something went wrong!