Question: Study the current TCP Socket based implementations of both the Echo Client and Server programs. Rewrite them to use UDP sockets in Java. See the
Study the current TCP Socket based implementations of both the Echo Client and Server programs. Rewrite them to use UDP sockets in Java. See the documentation for DatagramSockets etc. in the java docs for guidance.
Echo Client:-
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class EchoClient {
private static final int EXIT_FAILURE = 1;
public static void main(String[] args) throws IOException {
if (args.length != 2) {
System.err.printf("usage: java EchoClient
System.exit(EXIT_FAILURE);
}
String hostName = args[0];
int port = Integer.parseInt(args[1]);
try (
Socket echoSocket = new Socket(hostName, port);
PrintWriter socketOutput = new PrintWriter(echoSocket.getOutputStream(), true);
BufferedReader socketInput = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
BufferedReader console = new BufferedReader(new InputStreamReader(System.in))) {
String userInput;
while ((userInput = console.readLine()) != null) {
socketOutput.println(userInput);
System.out.println("echo: " + socketInput.readLine());
}
}
catch (UnknownHostException error) {
System.err.printf("unknown host: %s ", hostName);
System.exit(EXIT_FAILURE);
} catch (IOException error) {
System.err.printf("unable to establish I/O connection to %s ", hostName);
System.exit(EXIT_FAILURE);
}
}
Echo Server:-
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class EchoServer {
private static final int EXIT_FAILURE = 1;
public static void main(String[] args) throws IOException {
if (args.length != 1) {
System.err.printf("usage: java EchoServer
System.exit(EXIT_FAILURE);
}
int portNumber = Integer.parseInt(args[0]);
try (
ServerSocket serverSocket = new ServerSocket(Integer.parseInt(args[0]));
Socket clientSocket = serverSocket.accept();
PrintWriter clientOutput = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader clientInput = new BufferedReader( new InputStreamReader(clientSocket.getInputStream()))) {
String inputLine;
while ((inputLine = clientInput.readLine()) != null)
{ clientOutput.println(inputLine);
}
}
catch (IOException error)
{
System.out.printf("error when trying to listen on port %d or listening for connection ",portNumber);
System.out.println(error.getMessage());
}
}
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
