Name: Brian Mwangi Makhembu
Reg no: CS282-6772/2013
Unit Code: BIT 2312
Unit: Client Server Computing System
Practical CAT
Talk Server Java Application
Server-side code
import java.net.*;// contains all network libraries
import java.io.*;// allows input output string
import java.util.*; //Scanner to prompt user input
public class TalkServer extends Thread
{
private ServerSocket serverSocket; //declare a server socket object. Since
it's the client, only needs ports
Scanner input = new Scanner(System.in);
public TalkServer(int port) throws IOException //function to define server
socket, and specify timeout
{
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(20000);
}
public void run() //function to handle communication between server and
client
{
while(true) // loop to keep the client running indefinitely
{
try
{
Socket server = serverSocket.accept(); // create a socket
object with a connection from a client
DataInputStream in = new
DataInputStream(server.getInputStream());
System.out.println(in.readUTF()); // read the output from the
server, and print it out on console
DataOutputStream out = new
DataOutputStream(server.getOutputStream());
out.writeUTF("Hi, I'm "+ server.getLocalSocketAddress() + "\
ntalk to me!"); // send the initial message and
while (true){
String st = new String(in.readUTF()); // read the message
from the client
System.out.print(st); // print out client's message to
screen
out.writeUTF("SERVER>> " + input.nextLine() + "\
nresponse<< "); // send reply to client
}
}catch(SocketTimeoutException s) // catch timeout error
{
System.out.println("socket timed out!");
break;
}catch(IOException e)
{
System.out.print("Error occurred; ");
e.printStackTrace();
break;
}
}
}
public static void main(String [] args) //main function, where execution
should start
{
int port = 5050;
try
{
Thread t = new TalkServer(port);
t.start();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
Client-Side Code
import java.net.*;
import java.io.*;
import java.util.*;
public class TalkClient
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
String serverName = "localhost";
int port = Integer.parseInt("5050");
try
{
Socket client = new Socket (serverName, port);
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
out.writeUTF("Hello from " + client.getLocalSocketAddress());
InputStream inFromServer = client.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
System.out.println(in.readUTF());
while(true){
String toServer = "CLIENT>> ";
toServer = toServer + input.nextLine();
out.writeUTF(toServer + "\nresponse<< ");
String st = new String (in.readUTF());
System.out.print(st);
}
}catch(IOException e)
{
e.printStackTrace();
}
}
}
SCREENSHOTS
Server screenshot
Client Screenshot