Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write two programs (using programming language of your choice) or two algorithms

ID: 3810942 • Letter: W

Question

Write two programs (using programming language of your choice) or two algorithms or two pseudo codes or two flow charts, where one of them acts as a simple client reading a line from its standard input (keyboard) and send it out to the server. The other program acts as a simple server and converts anything the client sent to uppercase and sends it back to the client. The client then should print the line on its standard output (monitor).

(i) Please provide the client-server program pair for a TCP implementation.

(ii) Moreover, discuss whether it would be different or not of it were a UDP implementation.

Explanation / Answer

Server.java

package tcp;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

   public static void main(String a[])throws Exception{
      
       ServerSocket ss=new ServerSocket(6789);
      
       Socket s=ss.accept();
      
       BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
       String line="";
       String cliMsg="";
       while((line=br.readLine())!=null){
       line=line.toUpperCase();
       cliMsg+=line;
       }
      
       DataOutputStream dos=new DataOutputStream(s.getOutputStream());
       dos.writeBytes(cliMsg);
      
       br.close();
       dos.close();
   }
}

Client.java

package tcp;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.Socket;

public class Client {

       public static void main(String a[]) throws Exception{
           String sentence;
           String modifiedSentence;
           BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
           Socket clientSocket = new Socket("localhost", 6789);
           DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
           BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
           sentence = inFromUser.readLine();
           outToServer.writeBytes(sentence + ' ');
           modifiedSentence = inFromServer.readLine();
           System.out.println("FROM SERVER: " + modifiedSentence);
           clientSocket.close();
          
       }
}