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

Practice socket programming with threads: Write an \'echo\' server using UDP . (

ID: 3863891 • Letter: P

Question

Practice socket programming with threads: Write an 'echo' server using UDP. (This server does not need to be multi-threaded, but make sure that you do know how to implement a multi-threaded server when asked.) Each request is handled by replying to the client with the unmodified string the client sent.

Also, write an 'echo' client to test your server. Each client will send 20 sequentially numbered messages to the server & receive the replies. This code needs to be in java.

Need two features:

1. request is handled by replying to the client with the unmodified string the client sent.

2. 20 sequentially numbered messages to the server & receive the replies

Explanation / Answer

Server.java

import java.io.*;
import java.net.*;

public class Server{
   public static void main(String args[]) throws IOException{
      
       //Creating server socket on the port 1234
       ServerSocket serverSocket = new ServerSocket(1234);
       //Establishing the connection with client
       Socket socket = serverSocket.accept();
       //Initializing the streams for reading and writing the data
       DataInputStream dis = new DataInputStream(socket.getInputStream());
       DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
       while(true){
           //Reading the data from client
           String str = (String)dis.readUTF();
           //Echo back to the client
           dos.writeUTF(str);
           dos.flush();
       }
   }
}

Client.java

import java.io.*;
import java.net.*;

class Client{
   public static void main(String args[]) throws IOException{
       System.out.println("Client program");
       //Opening the connection with the server on the port 1234
       Socket socket=new Socket("localhost",1234);
       //Input and Output streams for reading and writing the data
       DataInputStream dis = new DataInputStream(socket.getInputStream());
       DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
       for(int i=0;i<20;i++){
           //Writing the echo message to server
           dos.writeUTF("echo");
           //Receive a reply from server
           String read = dis.readUTF();
           System.out.println("Read "+read);
       }
       dos.flush();
       dos.close();
   }
}

OUTPUT :

echo
echo
echo
echo
echo
echo
echo
echo
echo
echo
echo
echo
echo
echo
echo
echo
echo
echo
echo
echo

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote