Computer Netwroks Lab (Ncs-651)

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 36

Lab Manual – Computer Networks Lab

LIST OF EXPERIMENTS
Date of
S. No. Objective Remark Sign
Submission
a) PROGRAM USING TCP SOCKETS
DATE AND TIME SERVER
1.
b) IMPLEMENTATION OF TCP/IP
ECHO
Programs using UDP Sockets (like simple
3. DNS)

Programs using Raw sockets (like packet


4. capturing and filtering)

Programs using RPC


5.
Simulation of sliding window protocols
6.

1
Lab Manual – Computer Networks Lab

Experiment 1: Programs using TCP Sockets (like date and time server & client, echo
server & client, etc.)
1. a) PROGRAM USING TCP SOCKETS DATE AND TIME SERVER

AIM:
To implement date and time display from client to server using TCP Sockets

DESCRIPTION:
TCP Server gets the system date and time and opens the server socket to read the client
Details. Client sends its address to the server. Then client receives the date and time from server
to display. TCP socket server client connection is opened for communication. After the date
time is displayed the server client connection is closed with its respective streams to be closed.

ALGORITHM:
Server
1. Create a server socket and bind it to port.
2. Listen for new connection and when a connection arrives, accept it.
3. Send server’s date and time to the client.
4. Read client’s IP address sent by the client.
5. Display the client details.
6. Repeat steps 2-5 until the server is terminated.
7. Close all streams.
8. Close the server socket.
9. Stop.
Client
1. Create a client socket and connect it to the server’s port number.
2. Retrieve its own IP address using built-in function.
3. Send its address to the server.
4. Display the date & time sent by the server.
5. Close the input and output streams.
6. Close the client socket.
7. Stop.

PROGRAM:
Server_DT.java
import java.net.*;
import java.io.*;
import java.util.Date;
public class Server_DT {
public static void main(String[] args)throws IOException {
// TODO code application logic here

//Step 1. Reserve a port number on the Server to offer this service


ServerSocket ss= new ServerSocket(5000);

2
Lab Manual – Computer Networks Lab

//(Optional)To confirm Server Reserved specified port or not


System.out.println("The Server has reserved port No.: "+ss.getLocalPort()+" for this Service");

//Step 2. Now create a Client Socket on Server for Bidirectonal Communication.


//Socket is created only when client communicates with the server
Socket cs=ss.accept();

//To confirm Server communicated through the socket or not

System.out.println("Client with IP Address "+cs.getInetAddress()+" has communicated via port No.:


"+cs.getPort());

Date d=new Date();


String s="Current Date & Time on Server is:"+d;

//Send String s to client via client socket


PrintWriter toclient=new PrintWriter(cs.getOutputStream(),true);
toclient.print(s);
toclient.close();
cs.close();
ss.close();
}
}

Client_DT.java
import java.net.*;
import java.io.*;
import java.util.Date;
public class Client_DT {
public static void main(String[] args) throws UnknownHostException,IOException {
// TODO code application logic here
//Step 1. Create a client socket to connect to Server
Socket cs= new Socket("LocalHost",5000);

//To confirm Client is communicating through the port


System.out.println("Client "+cs.getInetAddress()+" is communicating from port No.: "+cs.getPort());

//Receive Date Sent by Server


BufferedReader fromserver=new BufferedReader(new InputStreamReader(cs.getInputStream()));

System.out.println(fromserver.readLine());
fromserver.close();
cs.close();
}
}

OUTPUT
Server:

3
Lab Manual – Computer Networks Lab

Client:

RESULT:
Thus the program for implementing to display date and time from client to server using TCP
Sockets was executed successfully and output verified using various samples.

1. b) IMPLEMENTATION OF TCP/IP ECHO

AIM:
To implementation of echo client server using TCP/IP

DESCRIPTION:
TCP Server gets the message and opens the server socket to read the client details. Client
send its address to the server. Then client receives the message from server to display.

ALGORITHM
Server
1. Create a server socket and bind it to port.

4
Lab Manual – Computer Networks Lab

2. Listen for new connection and when a connection arrives, accept it.
3. Read the data from client.
4. Echo the data back to the client.
5. Repeat steps 4-5 until „bye‟ or „null‟ is read.
6. Close all streams.
7. Close the server socket.
8. Stop.
Client
1. Create a client socket and connect it to the server’s port number.
2. Get input from user.
3. If equal to bye or null, then go to step 7.
4. Send user data to the server.
5. Display the data echoed by the server.
6. Repeat steps 2-4.
7. Close the input and output streams.
8. Close the client socket.
9. Stop

PROGRAM:

Server
import java.net.*;
import java.io.*;
public class tcpechoserver
{
public static void main(String[] arg) throws IOException
{
ServerSocket sock = null; BufferedReader fromClient = null; OutputStreamWriter toClient = null; Socket client =
null;
try
{
sock = new ServerSocket(4000); System.out.println("Server Ready");

client = sock.accept(); System.out.println("Client Connected"); fromClient = new BufferedReader(new


InputStreamReader(client.getInputStream()));
toClient = new OutputStreamWriter(client.getOutputStream()); String line;
while (true)
{
line = fromClient.readLine();
if ( (line == null) || line.equals("bye"))
break;
System.out.println ("Client [ " + line + " ]"); toClient.write("Server [ "+ line +" ]\n"); toClient.flush();
} fromClient.close(); toClient.close(); client.close(); sock.close();
System.out.println("Client Disconnected");
}
catch (IOException ioe)
{ System.err.println(ioe);
}
}

5
Lab Manual – Computer Networks Lab

Client
import java.net.*;
import java.io.*;
public class tcpechoclient
{
public static void main(String[] args) throws IOException
{
BufferedReader fromServer = null, fromUser = null; PrintWriter toServer = null;
Socket sock = null;
try
{
if(args.length == 0)
sock = new Socket(InetAddress.getLocalHost(),4000);
else
sock = new Socket(InetAddress.getByName(args[0]),4000); fromServer = new
BufferedReader(new InputStreamReader(sock.getInputStream()));
fromUser = new BufferedReader(new InputStreamReader(System.in));
toServer = new PrintWriter(sock.getOutputStream(),true); String Usrmsg, Srvmsg;
System.out.println("Type \"bye\" to quit");
while (true)
{
System.out.print("Enter msg to server : "); Usrmsg = fromUser.readLine();
if (Usrmsg==null || Usrmsg.equals("bye"))
{
toServer.println("bye"); break;
}
else toServer.println(Usrmsg);
Srvmsg = fromServer.readLine(); System.out.println(Srvmsg);
}
fromUser.close();
fromServer.close();
toServer.close();
sock.close();
}
catch (IOException ioe)
{
System.err.println(ioe);
}
}
}

OUTPUT
Server:
$ javac tcpechoserver.java
$ java tcpechoserver
Server Ready Client Connected Client [ hello ]
Client [ how are you ] Client [ i am fine ] Client [ ok ] Client Disconnected
Client:

6
Lab Manual – Computer Networks Lab

$ javac tcpechoclient.java
$ java tcpechoclient
Type "bye" to quit
Enter msg to server : hello
Server [ hello ]
Enter msg to server : how are you
Server [ how are you ]
Enter msg to server : i am fine
Server [ i am fine ]
Enter msg to server : ok
Server [ ok ]
Enter msg to server : bye

RESULT
Thus data from client to server is echoed back to the client to check reliability/noise level of the
channel.

7
Lab Manual – Computer Networks Lab

8
Lab Manual – Computer Networks Lab

EXPERIMENT 2: UDP DNS SERVER/CLIENT


AIM:
To implement a DNS server and client in java using UDP sockets.

DESCRIPTION
DNS stands for domain name system. Unique name of the host is identified with its IP address
through server client communication.

ALGORITHM:
Server
1. Create an array of hosts and its ip address in another array
2. Create a datagram socket and bind it to a port
3. Create a datagram packet to receive client request
4. Read the domain name from client to be resolved
5. Lookup the host array for the domain name
6. If found then retrieve corresponding address
7. Create a datagram packet and send ip address to client
8. Repeat steps 3-7 to resolve further requests from clients
9. Close the server socket
10. Stop

Client
1. Create a datagram socket
2. Get domain name from user
3. Create a datagram packet and send domain name to the server
4. Create a datagram packet to receive server message5. Read server's response
6. If ip address then display it else display "Domain does not exist"
7. Close the client socket
8. Stop

PROGRAM
// UDP DNS Server -- udpdnsserver.java
import java.io.*;
import java.net.*;
public class udpdnsserver
{

9
Lab Manual – Computer Networks Lab

private static int indexOf(String[] array, String str)


{
str = str.trim();
for (int i=0; i < array.length; i++)
{
if (array[i].equals(str))
return i;
}
return -1;
}
public static void main(String arg[])throws IOException
{
String[] hosts = {"yahoo.com", "gmail.com","cricinfo.com", "facebook.com"}; String[] ip = {"68.180.206.184",
"209.85.148.19","80.168.92.140", "69.63.189.16"};
System.out.println("Press Ctrl + C to Quit");
while (true)
{
DatagramSocket serversocket=new DatagramSocket(1362);
byte[] senddata = new byte[1021]; byte[] receivedata = new byte[1021]; DatagramPacket recvpack = new
DatagramPacket(receivedata, receivedata.length); serversocket.receive(recvpack);
String sen = new String(recvpack.getData()); InetAddress ipaddress = recvpack.getAddress(); int port =
recvpack.getPort();
String capsent;
System.out.println("Request for host " + sen);
if(indexOf (hosts, sen) != -1) capsent = ip[indexOf (hosts, sen)]; else
capsent = "Host Not Found";
senddata = capsent.getBytes();
DatagramPacket pack = new DatagramPacket(senddata, senddata.length,ipaddress,port); serversocket.send(pack);
serversocket.close();
}
}
}
//UDP DNS Client -- udpdnsclient.java
import java.io.*;
import java.net.*;
public class udpdnsclient
{
public static void main(String args[])throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); DatagramSocket clientsocket =
new DatagramSocket();
InetAddress ipaddress;
if (args.length == 0)
ipaddress = InetAddress.getLocalHost();

10
Lab Manual – Computer Networks Lab

else
ipaddress = InetAddress.getByName(args[0]);
byte[] senddata = new byte[1024]; byte[] receivedata = new byte[1024]; int portaddr = 1362;
System.out.print("Enter the hostname : "); String sentence = br.readLine();
Senddata = sentence.getBytes();
DatagramPacket pack = new DatagramPacket(senddata,senddata.length, ipaddress,portaddr);
clientsocket.send(pack);
DatagramPacket recvpack =new DatagramPacket(receivedata,receivedata.length);
clientsocket.receive(recvpack);
String modified = new String(recvpack.getData()); System.out.println("IP Address: " + modified);
clientsocket.close();
}
}

OUTPUT
Server
$ javac udpdnsserver.java
$ java udpdnsserver Press Ctrl + C to Quit Request for host yahoo.com
Request for host cricinfo.com
Request for host youtube.com

Client
$ javac udpdnsclient.java
$ java udpdnsclient
Enter the hostname : yahoo.com
IP Address: 68.180.206.184
$ java udpdnsclient
Enter the hostname : cricinfo.com
IP Address: 80.168.92.140
$ java udpdnsclient
Enter the hostname : youtube.com
IP Address: Host Not Found

RESULT
Thus domain name requests by the client are resolved into their respective logical address using
lookup method.

11
Lab Manual – Computer Networks Lab

EXPERIMENT 3: Programs using Raw sockets (like packet capturing and filtering)
AIM:
12
Lab Manual – Computer Networks Lab

To implement a TicTacToe server and client in java using Raw sockets.


PROGRAM
CLIENT
//package edu.lmu.cs.networking;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

/**
* A client for the TicTacToe game, modified and extended from the
* class presented in Deitel and Deitel "Java How to Program" book.
* I made a bunch of enhancements and rewrote large sections of the
* code. In particular I created the TTTP (Tic Tac Toe Protocol)
* which is entirely text based. Here are the strings that are sent:
*
* Client -> Server Server -> Client
* ---------------- ----------------
* MOVE <n> (0 <= n <= 8) WELCOME <char> (char in {X, O})
* QUIT VALID_MOVE
* OTHER_PLAYER_MOVED <n>
* VICTORY
* DEFEAT

13
Lab Manual – Computer Networks Lab

* TIE
* MESSAGE <text>
*
*/
public class TicTacToeClient {

private JFrame frame = new JFrame("Tic Tac Toe");


private JLabel messageLabel = new JLabel("");
private ImageIcon icon;
private ImageIcon opponentIcon;

private Square[] board = new Square[9];


private Square currentSquare;

private static int PORT = 8901;


private Socket socket;
private BufferedReader in;
private PrintWriter out;

/**
* Constructs the client by connecting to a server, laying out the
* GUI and registering GUI listeners.
*/
public TicTacToeClient(String serverAddress) throws Exception {

// Setup networking
socket = new Socket(serverAddress, PORT);
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);

// Layout GUI
messageLabel.setBackground(Color.lightGray);
frame.getContentPane().add(messageLabel, "South");

14
Lab Manual – Computer Networks Lab

JPanel boardPanel = new JPanel();


boardPanel.setBackground(Color.black);
boardPanel.setLayout(new GridLayout(3, 3, 2, 2));
for (int i = 0; i < board.length; i++) {
final int j = i;
board[i] = new Square();
board[i].addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
currentSquare = board[j];
out.println("MOVE " + j);}});
boardPanel.add(board[i]);
}
frame.getContentPane().add(boardPanel, "Center");
}

/**
* The main thread of the client will listen for messages
* from the server. The first message will be a "WELCOME"
* message in which we receive our mark. Then we go into a
* loop listening for "VALID_MOVE", "OPPONENT_MOVED", "VICTORY",
* "DEFEAT", "TIE", "OPPONENT_QUIT or "MESSAGE" messages,
* and handling each message appropriately. The "VICTORY",
* "DEFEAT" and "TIE" ask the user whether or not to play
* another game. If the answer is no, the loop is exited and
* the server is sent a "QUIT" message. If an OPPONENT_QUIT
* message is recevied then the loop will exit and the server
* will be sent a "QUIT" message also.
*/
public void play() throws Exception {
String response;
try {
response = in.readLine();
if (response.startsWith("WELCOME")) {

15
Lab Manual – Computer Networks Lab

char mark = response.charAt(8);


icon = new ImageIcon(mark == 'X' ? "x.gif" : "o.gif");
opponentIcon = new ImageIcon(mark == 'X' ? "o.gif" : "x.gif");
frame.setTitle("Tic Tac Toe - Player " + mark);
}
while (true) {
response = in.readLine();
if (response.startsWith("VALID_MOVE")) {
messageLabel.setText("Valid move, please wait");
currentSquare.setIcon(icon);
currentSquare.repaint();
} else if (response.startsWith("OPPONENT_MOVED")) {
int loc = Integer.parseInt(response.substring(15));
board[loc].setIcon(opponentIcon);
board[loc].repaint();
messageLabel.setText("Opponent moved, your turn");
} else if (response.startsWith("VICTORY")) {
messageLabel.setText("You win");
break;
} else if (response.startsWith("DEFEAT")) {
messageLabel.setText("You lose");
break;
} else if (response.startsWith("TIE")) {
messageLabel.setText("You tied");
break;
} else if (response.startsWith("MESSAGE")) {
messageLabel.setText(response.substring(8));
}
}
out.println("QUIT");
}
finally {
socket.close();
}

16
Lab Manual – Computer Networks Lab

private boolean wantsToPlayAgain() {


int response = JOptionPane.showConfirmDialog(frame,
"Want to play again?",
"Tic Tac Toe is Fun Fun Fun",
JOptionPane.YES_NO_OPTION);
frame.dispose();
return response == JOptionPane.YES_OPTION;
}

/**
* Graphical square in the client window. Each square is
* a white panel containing. A client calls setIcon() to fill
* it with an Icon, presumably an X or O.
*/
static class Square extends JPanel {
JLabel label = new JLabel((Icon)null);

public Square() {
setBackground(Color.white);
add(label);
}

public void setIcon(Icon icon) {


label.setIcon(icon);
}
}

/**
* Runs the client as an application.
*/
public static void main(String[] args) throws Exception {
while (true) {

17
Lab Manual – Computer Networks Lab

String serverAddress = (args.length == 0) ? "localhost" : args[1];


TicTacToeClient client = new TicTacToeClient(serverAddress);
client.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
client.frame.setSize(240, 160);
client.frame.setVisible(true);
client.frame.setResizable(false);
client.play();
if (!client.wantsToPlayAgain()) {
break;
}
}
}
}

SERVER
//package edu.lmu.cs.networking;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
* A server for a network multi-player tic tac toe game. Modified and
* extended from the class presented in Deitel and Deitel "Java How to
* Program" book. I made a bunch of enhancements and rewrote large sections
* of the code. The main change is instead of passing *data* between the
* client and server, I made a TTTP (tic tac toe protocol) which is totally
* plain text, so you can test the game with Telnet (always a good idea.)
* The strings that are sent in TTTP are:
*
* Client -> Server Server -> Client

18
Lab Manual – Computer Networks Lab

* ---------------- ----------------
* MOVE <n> (0 <= n <= 8) WELCOME <char> (char in {X, O})
* QUIT VALID_MOVE
* OTHER_PLAYER_MOVED <n>
* VICTORY
* DEFEAT
* TIE
* MESSAGE <text>
*
* A second change is that it allows an unlimited number of pairs of
* players to play.
*/
public class TicTacToeServer {

/**
* Runs the application. Pairs up clients that connect.
*/
public static void main(String[] args) throws Exception {
ServerSocket listener = new ServerSocket(8901);
System.out.println("Tic Tac Toe Server is Running");
try {
while (true) {
Game game = new Game();
Game.Player playerX = game.new Player(listener.accept(), 'X');
Game.Player playerO = game.new Player(listener.accept(), 'O');
playerX.setOpponent(playerO);
playerO.setOpponent(playerX);
game.currentPlayer = playerX;
playerX.start();
playerO.start();
}
} finally {
listener.close();
}

19
Lab Manual – Computer Networks Lab

}
}

/**
* A two-player game.
*/
class Game {

/**
* A board has nine squares. Each square is either unowned or
* it is owned by a player. So we use a simple array of player
* references. If null, the corresponding square is unowned,
* otherwise the array cell stores a reference to the player that
* owns it.
*/
private Player[] board = {
null, null, null,
null, null, null,
null, null, null};

/**
* The current player.
*/
Player currentPlayer;

/**
* Returns whether the current state of the board is such that one
* of the players is a winner.
*/
public boolean hasWinner() {
return
(board[0] != null && board[0] == board[1] && board[0] == board[2])
||(board[3] != null && board[3] == board[4] && board[3] == board[5])
||(board[6] != null && board[6] == board[7] && board[6] == board[8])

20
Lab Manual – Computer Networks Lab

||(board[0] != null && board[0] == board[3] && board[0] == board[6])


||(board[1] != null && board[1] == board[4] && board[1] == board[7])
||(board[2] != null && board[2] == board[5] && board[2] == board[8])
||(board[0] != null && board[0] == board[4] && board[0] == board[8])
||(board[2] != null && board[2] == board[4] && board[2] == board[6]);
}

/**
* Returns whether there are no more empty squares.
*/
public boolean boardFilledUp() {
for (int i = 0; i < board.length; i++) {
if (board[i] == null) {
return false;
}
}
return true;
}

/**
* Called by the player threads when a player tries to make a
* move. This method checks to see if the move is legal: that
* is, the player requesting the move must be the current player
* and the square in which she is trying to move must not already
* be occupied. If the move is legal the game state is updated
* (the square is set and the next player becomes current) and
* the other player is notified of the move so it can update its
* client.
*/
public synchronized boolean legalMove(int location, Player player) {
if (player == currentPlayer && board[location] == null) {
board[location] = currentPlayer;
currentPlayer = currentPlayer.opponent;
currentPlayer.otherPlayerMoved(location);

21
Lab Manual – Computer Networks Lab

return true;
}
return false;
}

/**
* The class for the helper threads in this multithreaded server
* application. A Player is identified by a character mark
* which is either 'X' or 'O'. For communication with the
* client the player has a socket with its input and output
* streams. Since only text is being communicated we use a
* reader and a writer.
*/
class Player extends Thread {
char mark;
Player opponent;
Socket socket;
BufferedReader input;
PrintWriter output;

/**
* Constructs a handler thread for a given socket and mark
* initializes the stream fields, displays the first two
* welcoming messages.
*/
public Player(Socket socket, char mark) {
this.socket = socket;
this.mark = mark;
try {
input = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
output = new PrintWriter(socket.getOutputStream(), true);
output.println("WELCOME " + mark);
output.println("MESSAGE Waiting for opponent to connect");

22
Lab Manual – Computer Networks Lab

} catch (IOException e) {
System.out.println("Player died: " + e);
}
}

/**
* Accepts notification of who the opponent is.
*/
public void setOpponent(Player opponent) {
this.opponent = opponent;
}

/**
* Handles the otherPlayerMoved message.
*/
public void otherPlayerMoved(int location) {
output.println("OPPONENT_MOVED " + location);
output.println(
hasWinner() ? "DEFEAT" : boardFilledUp() ? "TIE" : "");
}

/**
* The run method of this thread.
*/
public void run() {
try {
// The thread is only started after everyone connects.
output.println("MESSAGE All players connected");

// Tell the first player that it is her turn.


if (mark == 'X') {
output.println("MESSAGE Your move");
}

23
Lab Manual – Computer Networks Lab

// Repeatedly get commands from the client and process them.


while (true) {
String command = input.readLine();
if (command.startsWith("MOVE")) {
int location = Integer.parseInt(command.substring(5));
if (legalMove(location, this)) {
output.println("VALID_MOVE");
output.println(hasWinner() ? "VICTORY"
: boardFilledUp() ? "TIE"
: "");
} else {
output.println("MESSAGE ?");
}
} else if (command.startsWith("QUIT")) {
return;
}
}
} catch (IOException e) {
System.out.println("Player died: " + e);
} finally {
try {socket.close();} catch (IOException e) {}
}
}
}
}

24
Lab Manual – Computer Networks Lab

EXPERIMENT 4: Programs using Programs using RPC (like ChatServer)

AIM:
To implement a multi ChatServer in java using RPC.

ChatServer
//package edu.lmu.cs.networking;
import java.io.BufferedReader;

25
Lab Manual – Computer Networks Lab

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashSet;

/**
* A multithreaded chat room server. When a client connects the
* server requests a screen name by sending the client the
* text "SUBMITNAME", and keeps requesting a name until
* a unique one is received. After a client submits a unique
* name, the server acknowledges with "NAMEACCEPTED". Then
* all messages from that client will be broadcast to all other
* clients that have submitted a unique screen name. The
* broadcast messages are prefixed with "MESSAGE ".
*
* Because this is just a teaching example to illustrate a simple
* chat server, there are a few features that have been left out.
* Two are very useful and belong in production code:
*
* 1. The protocol should be enhanced so that the client can
* send clean disconnect messages to the server.
*
* 2. The server should do some logging.
*/
public class ChatServer {

/**
* The port that the server listens on.
*/
private static final int PORT = 9001;

/**

26
Lab Manual – Computer Networks Lab

* The set of all names of clients in the chat room. Maintained


* so that we can check that new clients are not registering name
* already in use.
*/
private static HashSet<String> names = new HashSet<String>();

/**
* The set of all the print writers for all the clients. This
* set is kept so we can easily broadcast messages.
*/
private static HashSet<PrintWriter> writers = new HashSet<PrintWriter>();

/**
* The appplication main method, which just listens on a port and
* spawns handler threads.
*/
public static void main(String[] args) throws Exception {
System.out.println("The chat server is running.");
ServerSocket listener = new ServerSocket(PORT);
try {
while (true) {
new Handler(listener.accept()).start();
}
} finally {
listener.close();
}
}

/**
* A handler thread class. Handlers are spawned from the listening
* loop and are responsible for a dealing with a single client
* and broadcasting its messages.
*/
private static class Handler extends Thread {

27
Lab Manual – Computer Networks Lab

private String name;


private Socket socket;
private BufferedReader in;
private PrintWriter out;

/**
* Constructs a handler thread, squirreling away the socket.
* All the interesting work is done in the run method.
*/
public Handler(Socket socket) {
this.socket = socket;
}

/**
* Services this thread's client by repeatedly requesting a
* screen name until a unique one has been submitted, then
* acknowledges the name and registers the output stream for
* the client in a global set, then repeatedly gets inputs and
* broadcasts them.
*/
public void run() {
try {

// Create character streams for the socket.


in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);

// Request a name from this client. Keep requesting until


// a name is submitted that is not already used. Note that
// checking for the existence of a name and adding the name
// must be done while locking the set of names.
while (true) {
out.println("SUBMITNAME");

28
Lab Manual – Computer Networks Lab

name = in.readLine();
if (name == null) {
return;
}
synchronized (names) {
if (!names.contains(name)) {
names.add(name);
break;
}
}
}

// Now that a successful name has been chosen, add the


// socket's print writer to the set of all writers so
// this client can receive broadcast messages.
out.println("NAMEACCEPTED");
writers.add(out);

// Accept messages from this client and broadcast them.


// Ignore other clients that cannot be broadcasted to.
while (true) {
String input = in.readLine();
if (input == null) {
return;
}
for (PrintWriter writer : writers) {
writer.println("MESSAGE " + name + ": " + input);
}
}
} catch (IOException e) {
System.out.println(e);
} finally {
// This client is going down! Remove its name and its print
// writer from the sets, and close its socket.

29
Lab Manual – Computer Networks Lab

if (name != null) {
names.remove(name);
}
if (out != null) {
writers.remove(out);
}
try {
socket.close();
} catch (IOException e) {
}
}
}
}
}

ChatClient

//package edu.lmu.cs.networking;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.net.Socket;

import javax.swing.JFrame;

import javax.swing.JOptionPane;

import javax.swing.JScrollPane;

30
Lab Manual – Computer Networks Lab

import javax.swing.JTextArea;

import javax.swing.JTextField;

/**

* A simple Swing-based client for the chat server. Graphically

* it is a frame with a text field for entering messages and a

* textarea to see the whole dialog.

* The client follows the Chat Protocol which is as follows.

* When the server sends "SUBMITNAME" the client replies with the

* desired screen name. The server will keep sending "SUBMITNAME"

* requests as long as the client submits screen names that are

* already in use. When the server sends a line beginning

* with "NAMEACCEPTED" the client is now allowed to start

* sending the server arbitrary strings to be broadcast to all

* chatters connected to the server. When the server sends a

* line beginning with "MESSAGE " then all characters following

* this string should be displayed in its message area.

*/

public class ChatClient {

BufferedReader in;

PrintWriter out;

31
Lab Manual – Computer Networks Lab

JFrame frame = new JFrame("Chatter");

JTextField textField = new JTextField(40);

JTextArea messageArea = new JTextArea(8, 40);

/**

* Constructs the client by laying out the GUI and registering a

* listener with the textfield so that pressing Return in the

* listener sends the textfield contents to the server. Note

* however that the textfield is initially NOT editable, and

* only becomes editable AFTER the client receives the NAMEACCEPTED

* message from the server.

*/

public ChatClient() {

// Layout GUI

textField.setEditable(false);

messageArea.setEditable(false);

frame.getContentPane().add(textField, "North");

frame.getContentPane().add(new JScrollPane(messageArea), "Center");

frame.pack();

// Add Listeners

textField.addActionListener(new ActionListener() {

32
Lab Manual – Computer Networks Lab

/**

* Responds to pressing the enter key in the textfield by sending

* the contents of the text field to the server. Then clear

* the text area in preparation for the next message.

*/

public void actionPerformed(ActionEvent e) {

out.println(textField.getText());

textField.setText("");

});

/**

* Prompt for and return the address of the server.

*/

private String getServerAddress() {

return JOptionPane.showInputDialog(

frame,

"Enter IP Address of the Server:",

"Welcome to the Chatter",

JOptionPane.QUESTION_MESSAGE);

33
Lab Manual – Computer Networks Lab

/**

* Prompt for and return the desired screen name.

*/

private String getName() {

return JOptionPane.showInputDialog(

frame,

"Choose a screen name:",

"Screen name selection",

JOptionPane.PLAIN_MESSAGE);

/**

* Connects to the server then enters the processing loop.

*/

private void run() throws IOException {

// Make connection and initialize streams

String serverAddress = getServerAddress();

Socket socket = new Socket(serverAddress, 9001);

in = new BufferedReader(new InputStreamReader(

socket.getInputStream()));

out = new PrintWriter(socket.getOutputStream(), true);

34
Lab Manual – Computer Networks Lab

// Process all messages from server, according to the protocol.

while (true) {

String line = in.readLine();

if (line.startsWith("SUBMITNAME")) {

out.println(getName());

} else if (line.startsWith("NAMEACCEPTED")) {

textField.setEditable(true);

} else if (line.startsWith("MESSAGE")) {

messageArea.append(line.substring(8) + "\n");

/**

* Runs the client as an application with a closeable frame.

*/

public static void main(String[] args) throws Exception {

ChatClient client = new ChatClient();

client.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

client.frame.setVisible(true);

client.run();

35
Lab Manual – Computer Networks Lab

36

You might also like