Practical 1
Aim : To implement reliable client-server communication using TCP Socket API.
Given Problem:
Write a java program where client sends a string as a message and
sever counts the characters in the received message from client. Server sends this
value back to the client. Server should be able to serve multiple clients
simultaneously.
Solution (Java Code) :
Client Side:
package practicals;
import java.net.*;
import java.io.*;
import java.util.*;
/**
*
* @author janvi
*/
public class Pract_1_Client {
public static void main(String[] args) {
try{
// Connect to the server
Socket s = new Socket("LocalHost",8085);
System.out.println("Connected to server!");
OutputStream out = s.getOutputStream();
DataOutputStream dout = new DataOutputStream(out);
Scanner sc = new Scanner(System.in);
System.out.println("Enter a message :");
String str = sc.nextLine();
dout.writeUTF(str);
dout.flush();
// answer from the server
InputStream in = s.getInputStream();
DataInputStream din = new DataInputStream(in);
String Final = din.readUTF();
System.out.println("Character count received from server:"+ Final);
// Close resources
din.close();
dout.close();
s.close();
sc.close();
}
catch(Exception e){
System.out.println("Client Error: " + e.getMessage());
}
}
}
Server Side :
package practicals;
import java.io.*;
import java.net.*;
import java.lang.*;
/**
* @author janvi
*/
public class Pract_1_Server {
public static void main(String[] args){
try{
ServerSocket ss = new ServerSocket(8085);
System.out.println("Server is running...");
while(true){
Socket s = ss.accept();
System.out.println("New client connected");
// Create a new thread for each client
new MyThread(s).start();
}
}
catch(Exception e){
}
}
}
class MyThread extends Thread {
private Socket s;
MyThread(Socket s){
this.s =s;
}
@Override
public void run(){
try{
InputStream in = s.getInputStream();
DataInputStream din = new DataInputStream(in);
System.out.println("From " + s.getRemoteSocketAddress());
// Reading message from client
String st = din.readUTF();
System.out.println("Received: " + st);
if (st != null) {
String length = String.valueOf(st.length());
// Send character count to client
OutputStream out = s.getOutputStream();
DataOutputStream dout = new DataOutputStream(out);
dout.writeUTF(length);
dout.flush();
System.out.println("Sent character count: " + length);
// Close streams and socket
dout.close();
din.close();
s.close();
}
}
catch(Exception e){
System.out.println("Error: " + e.getMessage());
}
}
}
Output :
Signature of Faculty Grade