Documente Academic
Documente Profesional
Documente Cultură
Source:
http://java.sun.com/docs/books/tutorial/networking/sockets/
Echo Client
The example program implements a client, EchoClient, that connects to the Echo server. The Echo server simply receives data from its client and echoes it back. The Echo server is a well-known service that clients can rendezvous with on port 7.
Let's walk through the program and investigate the interesting parts.
The three statements in the try block of the main method are critical. These lines establish the socket connection between the client and the server and open a PrintWriter and a BufferedReader on the socket:
echoSocket = new Socket("taranis", 7); out = new PrintWriter(echoSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader( echoSocket.getInputStream()));
The first statement in this sequence creates a new Socket object and names it echoSocket. This Socket constructor requires the name of the machine and the port number to which you want to connect. This program uses the host name taranis. This is the name of a hypothetical machine on our local network. When you type in and run this program on your machine, change the host name to the name of a machine on your network. Make sure that the name you use is the fully qualified IP name of the machine to which you want to connect.
The second argument is the port number. Port number 7 is the port on which the Echo server listens.
The second statement gets the socket's output stream and opens a PrintWriter on it.
The third statement gets the socket's input stream and opens a BufferedReader on it. The example uses readers and writers so that it can write Unicode characters over the socket.
Sending Data
To send data through the socket to the server, EchoClient simply needs to write to the PrintWriter. To get the server's response, EchoClient reads from the BufferedReader. The rest of the program achieves this.
While Loop
The while loop reads a line at a time from the standard input stream and immediately sends it to the server by writing it to the PrintWriter connected to the socket:
String userInput; while ((userInput = stdIn.readLine()) != null) { out.println(userInput); System.out.println("echo: "+in.readLine()); }
Housekeeping
out.close(); in.close(); stdIn.close(); echoSocket.close();
These lines of code fall into the category of house keeping. A well-behaved program always cleans up after itself, and this program is well-behaved. These statements close the readers and writers connected to the socket and to the standard input stream, and close the socket connection to the server. The order here is important. You should close any streams connected to a socket before you close the socket itself.
Summary
This client program is straightforward and simple because the Echo server implements a simple protocol. The client sends text to the server, and the server echoes it back. When your client programs are talking to a more complicated server such as an HTTP server, your client program will also be more complicated.
The Basics
Open a socket. Open an input stream and output stream to the socket. Read from and write to the stream according to the server's protocol. Close the streams. Close the socket. Only step 3 differs from client to client, depending on the server. The other steps remain largely the same.
When created, the QuoteServerThread class creates a DatagramSocket on port 4445 (arbitrarily chosen). This is the DatagramSocket through which the server communicates with all of its clients.
public QuoteServerThread() throws IOException { this("QuoteServer"); } public QuoteServerThread(String name) throws IOException { super(name); socket = new DatagramSocket(4445);
try { in = new BufferedReader( new FileReader("oneliners.txt")); } catch (FileNotFoundException e) System.err.println("Couldn't open quote file. " + "Serving time instead."); } }
Ports
A computer usually has one physical connection to the network. So all the data from the the network comes through this connection. If all the data comes through the same interface how does the computer redirect to specific applications? Recall, with IP network addresses
The computer is identified by its 32-bit IP address The port address is used to identify the specific program or application to send the packet to.
Ports
Port numbers range from 0 to 65,535 because ports are represented by 16-bit numbers. The port numbers ranging from 0 - 1023 are restricted. They are reserved for use by well-known services such as HTTP and FTP and other system services. Remember that certain ports are dedicated to wellknown services and you cannot use them. If you specify a port that is in use, the creation of the DatagramSocket will fail..
Constructor
The constructor also opens a BufferedReader on a file named oneliners.txt which contains a list of quotes. Each quote in the file is on a line by itself.
Run Method
Now for the interesting part of the QuoteServerThread: its run method. The run method overrides run in the Thread class and provides the implementation for the thread.
Run Method
The run method contains a while loop that continues as long as there are more quotes in the file. During each iteration of the loop, the thread waits for a DatagramPacket to arrive over the DatagramSocket. The packet indicates a request from a client. In response to the client's request, the QuoteServerThread gets a quote from the file, puts it in a DatagramPacket and sends it over the DatagramSocket to the client that asked for it.
The first statement creates an array of bytes which is then used to create a DatagramPacket.
DatagramPacket
The DatagramPacket will be used to receive a datagram from the socket because of the constructor used to create it. This constructor requires only two arguments: a byte array that contains client-specific data and the length of the byte array. When constructing a DatagramPacket to send over the DatagramSocket, you also must supply the Internet address and port number of the packet's destination. You'll see this later when we discuss how the server responds to a client request.
socket.receive(packet);
The last statement in the previous code snippet receives a datagram from the socket (the information received from the client gets copied into the packet). The receive method waits forever until a packet is received. If no packet is received, the server makes no further progress and just waits.
Server Clean up
When the server has read all the quotes from the quote file, the while loop terminates and the run method cleans up:
socket.close();
Local Variables
The QuoteClient class contains one method, the main method for the client application. The top of the main method declares several local variables for its use:
int port; InetAddress address; DatagramSocket socket = null; DatagramPacket packet; byte[] sendBuf = new byte[256];
The QuoteClient application requires one commandline argument: the name of the machine on which the QuoteServer is running.
Create Socket
The code segment gets the Internet address for the host named on the command line (presumably the name of the machine on which the server is running). This InetAddress and the port number 4445 (the port number that the server used to create its DatagramSocket) are then used to create DatagramPacket destined for that Internet address and port number. Therefore the DatagramPacket will be delivered to the quote server.
Note that the code creates a DatagramPacket with an empty byte array. The byte array is empty because this datagram packet is simply a request to the server for information. All the server needs to know to send a response--the address and port number to which reply--is automatically part of the packet.
getData Method
When the client receives a reply from the server, the client uses the getData method to retrieve that data from the packet. The client then converts the data to a string and displays it.
After you've successfully compiled the server and the client programs, you run them. You have to run the server program first. Just use the Java interpreter and specify the QuoteServer class name.
Once the server has started, you can run the client program. Remember to run the client program with one command-line argument: the name of the host on which the QuoteServer is running.
Output
After the client sends a request and receives a response from the server, you should see output similar to this:
Quote of the Moment: Good programming is 99% sweat and 1% coffee.
import java.net.*; import java.io.*; public class KKMultiServer { public static void main(String[] args) throws IOException { ServerSocket serverSocket = null; boolean listening = true; try { serverSocket = new ServerSocket(4444); } catch (IOException e) { System.err.println("Could not listen on port: 4444."); System.exit(-1); }
URL, URLConnection, Server Socket, InetAddress, and Socket Classes See Waite and Lafore, Object Oriented Programming in Java, chapter 16
URL
URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on the Internet. It is comprised of the following components, Protocol : //java.sun.com
URL Class
URL Class
Key Public Methods boolean equals(Object obj) Object getContent() String getFile() String getHost() String getPort() String getProtocol() String getRef() URLConnection openConnection InputStream openStream() boolean sameFile(URL doc)
URLConnection Class
Key Public Methods void connect() Object getContent() String getContentEncoding() int getContentLength() String getContentType() long getexpiration() String getHeaderField(String fieldname) String getHeaderField(int n) getInputStream() getLastModified() URL getURL()
InetAddress Class
Key Public Class Methods InetAddress[]getAllByName(String Host) (returns array) InetAddress getByName(String Host) InetAddress getLocalHost() Key Public Methods byte getAddress() String getHostName()
Socket Class
Key Constructors Socket(String host, int port) Socket(InetAddress ipNumber , int port) Key Public Methods void close() InetAddress getInetAddress() InputStream getInputStream() int getLocalPort() OutputStream getOutputStream() int get(Port()
Applet problems
If you have trouble running your program in an applet, it may be because you have not set the display property. The environment variable 'DISPLAY' tells UNIX where to display your windows. On a graphical workstation your DISPLAY value should be "computer_name:0" where you use the name of the computer in front of which you're sitting. Type setenv DISPLAY=chrome.njit.edu:0 if your computer's name is chrome.njit.edu.edu. The format for setting the DISPLAY variable may vary depending on the SHELL you are using.