Lab 1: Client and Server Programs: Objective
Lab 1: Client and Server Programs: Objective
Objective :
Information:
IP address
Every computer has an IP address. The IP address may be permanently assigned (a
static IP address), or it may be dynamically assigned (and possibly different every
time the computer is restarted). The IP address is like a phone number; the Client
program has to know the IP address of the computer it is trying to connect to (but
the Server program doesn't need to know the IP address of the computer that is
running the Client program). To find the IP address for a computer, open an MS-DOS
window and enter the command ipconfig. The IP address consists of four numbers
separated by periods, for example, 153.104.202.116 .
Port Number
The IP address gets you to the computer, but there might be many servers running
on the computer. Our Server needs to use a port number, which is like a telephone
extension. You can use any number you like between 1024 and 9999 for a port
number; the only requirement is that some other server isn't already using it. If
some other server is using it, you will get an error message that says so, and you
can just pick another number. (Numbers below 1024 are reserved for use by things
like FTP and HTTP servers). Your program could even use several different ports.
In the following code, I'm using my office phone number as a port number.
int PORT = 7486; // Any number between 1024 and 9999 will do
Since there are a lot of things that can go wrong, you need Exception handlers all
over the place. For simplicity, I'm going to ignore all the Exceptions, but they are in
the actual sample code.
Socket
Network programming revolves around the use of the socket object. As the name
suggests, a socket allows you to make a connection and "plug" two computers
together—albeit via a twisting path across cables, radio, and satellite links spreading
up to millions of kilometers. Every Internet application you have used works via
sockets. This includes Internet Explorer, Netscape, Eudora, CuteFTP, Napster, etc.
Java includes several classes for socket programming. The two classes that I use in
this article are java.net.ServerSocket, which encapsulates a server socket, and
java.net.Socket, which implements a client socket.
Lab Exercise:
Here are two short Java programs: one that acts as a client, one that acts as
a server. The client connects to the server, they exchange a couple of
messages and quit.
import java.net.*;
import java.io.*;
On the Server:
ServerSocket ss;
ss = new ServerSocket(PORT);
2. The server will sit and listen to the specified port, but it cannot actually
do anything until a connection is made to it. Thus, the Accept call must
be used to block execution of the program until a client makes a
request. When that happens, the accept method terminates, returning
a java.net.Socket object. In other words, when a client connects,
accept() returns a Socket for us to use.
Socket client;
client = ss.accept();
3. Define an input stream, so that we can read from this client. In this
example, our input stream is provided with text (Strings).
BufferedReader input;
input = new BufferedReader(
new InputStreamReader(client.getInputStream()));
PrintStream output;
output = new PrintStream(client.getOutputStream());
5. Read something. This code blocks waiting for input, so the client had
better send us something.
6. Write something.
output.println("Hello, Client!");
7. Quit. It is essential to close all the sockets; if you don't, the next time
you try to run the Server, the operating system may think those
sockets are still in use, and not let you have them.
input.close();
output.close();
client.close();
On the Client:
1. You have to know the IP address of the computer and the port number
of the server.
Note: You can run the client and the server on the same computer. If
you do, you can use either the actual IP address of that computer, or
the String "localhost".
2. Place a call to the server. This code "blocks"--that is, the program
doesn't go any further until the server responds, it just waits right
here. When the server responds, we have a Socket we can use.
3. Define an input stream, so that we can read from this client. In this
example, our input stream is provides text (Strings).
BufferedReader input;
input = new BufferedReader(
new InputStreamReader(server.getInputStream()));
PrintStream output;
output = new PrintStream(server.getOutputStream());
5. Write something.
output.println("Hello, Server!");
6. Read something. This code blocks waiting for input, so the server had
better send us something.
7. Quit.
Client.java
import java.net.*;
import java.io.*;
try {
// Call the server (and wait to be connected).
server = new Socket(IP_ADDRESS, PORT);
// Define input and output streams to server s
input = new BufferedReader(
new InputStreamReader(server.getInputStream()));
output = new PrintStream(server.getOutputStream());
// Write, then read. Without another thread, order is critical.
output.println("Hello, Server!");
String response = input.readLine(); // wait for input
System.out.println("Client got: " + response);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Server.java
import java.net.*;
import java.io.*;
try {
// Create the server socket
ss = new ServerSocket(PORT);
}
catch (Exception e) {
System.out.println("Failed to create ServerSocket.");
System.exit(0);
}
try {
// Wait for a client to connect (send us a socket)
client = ss.accept();
System.out.println("Just accepted a call from a client.");
// Associate reader and writer streams with that client.
// You could have an array of Sockets, one per client.
input = new BufferedReader(
new InputStreamReader(client.getInputStream()));
output = new PrintStream(client.getOutputStream());
// Read, then write. Without another thread, order is critical.
String message = input.readLine(); // sait for input
System.out.println("Server got: " + message);
output.println("Hello, Client!");
}
catch (Exception e) {
System.out.println("Failed to connect or do I/O.");
e.printStackTrace();
}
finally { // The sockets MUST be closed.
try {
input.close();
output.close();
client.close();
}
catch (Exception e) { // closing could cause an Exception
e.printStackTrace();
System.exit(0);
}
}
}