Write a Java program to design a protocol where a server is responsible to match
ID: 3662344 • Letter: W
Question
Write a Java program to design a protocol where a server is responsible to match up two chatter clients. The server listens on a TCP port for upcoming connections.
If no client is already connected to the server to be paired, the server accepts the connecting client, C1, and makes it wait for another client. To do that, it sends a “WAIT” command to C1. When receiving “WAIT”, C1 constructs a ServerSocket instance to listen on port p. Then it sends a message “CLIENT_PORT $p” to the server for future clients, where $p is the port number on which C1 listens for connections.
When another client, C2, seeks a connection with the server while C1 is waiting, the server informs C2 the existence of C1 by sending a message “PEER_LOC $h:$p” to C2, where $h is the host name (or IP address) of C1 and $p is the port number on which C1 is waiting. After C2 receives this message, it seeks a connection to C1 using the obtained information.
Clients get the messages from users. The two clients then exchange messages until either party, say C1, sends an end of stream” (Ctrl-D in Linux). In this case, C1 terminates the connection. Then C2 contacts the server. Depending upon the response it receives from the server, it either connects to another client that is currently waiting, or sends “CLIENT_PORT $p” to the server for future clients.
Explanation / Answer
Refer these codes..
The program works in a command-line interface where the users type in their messages. In this, the server waits for a connection from a single client and then closes down its listener so that no other clients can connect. After the client and server are connected, both ends of the connection work in much the same way. The user on the client end types a message, and it is transmitted to the server, which displays it to the user on that end. Then the user of the server types a message that is transmitted to the client. Then the client user types another message, and so on. This continues until one user or the other enters "quit" when prompted for a message. When that happens, the connection is closed and both programs terminate. The client program and the server program are very similar. The techniques for opening the connections differ, and the client is programmed to send the first message while the server is programmed to receive the first message.
/* This program is one end of a simple command-line interface chat program. It acts as a client which makes a
connection to the MyChatServer program. The computer to which the client is to connect must be specified as the
first command-line argument. The port on which the server listens can optionally be specified as the second command-line argument. If it is not, then the port specified by the constant DEFAULT_PORT is used.When the
connection is opened, each side sends the HANDSHAKE string to the other, so that both sides can verify that the program on the other end is of the right type.Then the connected programs alternate sending messages to each other.The client always sends the first message.The user on either end can close the connection by entering the string "quit" when prompted for a message. Note that the first character of any string sent over the connection is a
command, either MESSAGE or CLOSE.
*/
import java.net.*;
import java.io.*;
public class MyChatClient
{
static final int DEFAULT_PORT = 1728;
// Port where server is
// listening, if no
// port is specified
// on the command line.
static final String HANDSHAKE = "MyChat";
// Handshake string
// Each end of the connection sends this string
// to the other just after the connection is
// opened. This is done to confirm that the
// program on the other side of the connection
// is a myChat program.
static final char MESSAGE = '0';
// This character is prepended
// to every message that is sent.
static final char CLOSE = '1';
// This character is sent to
// the connected program when
// the user quits.
public static void main(String[] args)
{
String computer;
// The computer where the server is running,
// as specified on the command line. It can
// be either an IP number or a domain name.
int port;
// The port on which the server listens.
Socket connection;
// For communication with the server.
TextReader incoming;
// Stream for receiving data from server.
PrintWriter outgoing;
// Stream for sending data to server.
String messageOut;
// A message to be sent to the server.
String messageIn;
// A message received from the server.
/* First, get the computer from the command line.
Get the port from the command line, if one is specified,
or use the default port if none is specified. */
if (args.length == 0)
{
TextIO.putln("Usage: java SimpleClient <computer-name> [<port>]");
return;
}
computer = args[0];
if (args.length == 1)
port = DEFAULT_PORT;
else {
try {
port= Integer.parseInt(args[1]);
if (port <= 0 || port > 65535)
throw new NumberFormatException();
}
catch (NumberFormatException e)
{
TextIO.putln("Illegal port number, " + args[1]);
return;
}
}
/* Open a connetion to the server. Create streams for
communication and exchange the handshake. */
try {
TextIO.putln("Connecting to " + computer + " on port " + port);
connection = new Socket(computer,port);
incoming = new TextReader(connection.getInputStream());
outgoing = new PrintWriter(connection.getOutputStream());
outgoing.println(HANDSHAKE);
outgoing.flush();
messageIn = incoming.getln();
if (! messageIn.equals(HANDSHAKE) )
{
throw new IOException("Connected program is not MyChat!");
}
TextIO.putln("Connected. Enter your first message. ");
}
catch (Exception e)
{
TextIO.putln("An error occurred while opening connection.");
TextIO.putln(e.toString());
return;
}
/* Exchange messages with the other end of the connection
until one side or the other closes the connection.
This client program send the first message. After that,
messages alternate strictly back an forth. */
try {
while (true)
{
TextIO.put("SEND:");
messageOut = TextIO.getln();
if (messageOut.equalsIgnoreCase("quit"))
{
// User wants to quit. Inform the other side
// of the connection, then close the connection.
outgoing.println(CLOSE);
outgoing.flush();
connection.close();
TextIO.putln("Connection closed.");
break;
}
outgoing.println(MESSAGE + messageOut);
outgoing.flush();
if (outgoing.checkError())
{
throw new IOException("Error ocurred while reading incoming message.");
}
TextIO.putln("WAITING...");
messageIn = incoming.getln();
if (messageIn.length() > 0)
{
// The first character of the message is a command.
// If the command is CLOSE, then the connection
// is closed. Otherwise, remove the command
// character from the message and procede.
if (messageIn.charAt(0) == CLOSE)
{
TextIO.putln("Connection closed at other end.");
connection.close();
break;
}
messageIn = messageIn.substring(1);
}
TextIO.putln("RECEIVED: " + messageIn);
}
}
catch (Exception e)
{
TextIO.putln("Sorry, an error has occurred. Connection lost.");
TextIO.putln(e.toString());
System.exit(1);
}
} // end main()
} //end class MyChatClient
Remember that if you want to try out this program on a single computer, you can use two command-line windows. In one, give the command "java MyChatServer" to start the server. Then, in the other, use the command "java MyChatClient 127.0.0.1" to connect to the server that is running on the same machine.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.