Question
EXPLAIN EACH LINE OF CODE import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.Socket; import java.io.DataOutputStream; import java.io.EOFException; import java.io.IOException; import java.io.DataInputStream; public class ChatClient {
EXPLAIN EACH LINE OF CODE
import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.Socket; import java.io.DataOutputStream; import java.io.EOFException; import java.io.IOException; import java.io.DataInputStream;
public class ChatClient { public static void main(String[] args) { if (args.length != 1) { System.err.println("Usage: ChatServer "); return; }
try { int port = Integer.parseInt(args[0]);
Socket clientSocket = new Socket("localhost", port); CreateClient(clientSocket);
} catch (Exception e) { e.printStackTrace(); } }
private static void CreateClient(Socket clientSocket) throws IOException { // Initialize our input and output streams to operate off of the given client DataOutputStream output = new DataOutputStream(clientSocket.getOutputStream()); DataInputStream input = new DataInputStream(new BufferedInputStream(clientSocket.getInputStream())); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
// Create a thread that handles sending of messages (prevents blocking) Thread send = new Thread(new Runnable() { @Override public void run() { // Always run while the service is operational while (true) { try { String message = reader.readLine(); if (message == null) { System.out.println("Closing client."); clientSocket.shutdownInput(); clientSocket.shutdownOutput(); break; } output.writeUTF(message); } catch (IOException e) { e.printStackTrace(); break; } } } });
// thread that handles receiving of messages (prevents blocking) Thread receive = new Thread(new Runnable() { @Override public void run() { // Always run while the service is operational while (true) { try { if (clientSocket.isClosed()) break; String message = input.readUTF(); System.out.println(message); } catch (EOFException ex) { break; } catch (IOException e) { e.printStackTrace(); break; } } } });
// Start this handler's send and recieve threads. send.start(); receive.start(); } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started