You are on page 1of 6

STB 3103 Distributed Computing

Lab 1 : Client and Server Programs

Objective :

 To write a client program


 To write a server program
 To understand how client and server exchange messages

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.

Prepared by : Nazleeni Haron


STB 3103 Distributed Computing

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.

Both Client and Server have to import two essential packages:

import java.net.*;
import java.io.*;

On the Server:

1. Create a ServerSocket. This is used to accept calls from clients.

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()));

4. Define an output stream, so that we can write to this client. In this


example, our output stream is the one that accepts text (Strings).

PrintStream output;
output = new PrintStream(client.getOutputStream());

5. Read something. This code blocks waiting for input, so the client had
better send us something.

String message = input.readLine();

Prepared by : Nazleeni Haron


STB 3103 Distributed Computing

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.

String IP_ADDRESS = "153.104.202.116"; // Like a phone number


int PORT = 7486; // Like an extension

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.

server = new Socket(IP_ADDRESS, PORT);

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()));

4. Define an output stream, so that we can write to this client. In this


example, our output stream is one that accepts text (Strings).

PrintStream output;
output = new PrintStream(server.getOutputStream());

5. Write something.

output.println("Hello, Server!");

Prepared by : Nazleeni Haron


STB 3103 Distributed Computing

6. Read something. This code blocks waiting for input, so the server had
better send us something.

String response = input.readLine();

7. Quit.

To run these programs:

1. Open an MS-DOS window and run the server by typing java


Server. This step must be done first.
2. Open a second MS-DOS window and run the client by typing java
Client.

Client.java

import java.net.*;
import java.io.*;

public class Client {

public static void main(String args[]) {


Socket server; // our connection to the server
BufferedReader input;
PrintStream output;
String IP_ADDRESS = "153.104.202.116"; // Like a phone number
int PORT = 7486; // Like an extension

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();
}
}
}

Prepared by : Nazleeni Haron


STB 3103 Distributed Computing

Server.java

import java.net.*;
import java.io.*;

public class Server {

public static void main(String args[]) {


ServerSocket ss = null; // Switchboard used to make connection
Socket client = null; // After connection, use this for I/O
int PORT = 5654; // Any number between 1024 and 9999 will do
BufferedReader input = null;
PrintStream output = null;

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);
}
}
}

Prepared by : Nazleeni Haron


STB 3103 Distributed Computing

Prepared by : Nazleeni Haron

You might also like