Question
EXPLAIN EACH LINE OF CODE import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.io.BufferedInputStream; import java.net.Socket; import java.io.DataOutputStream; import java.io.EOFException; import java.io.IOException; import java.io.DataInputStream; public class
EXPLAIN EACH LINE OF CODE
import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.io.BufferedInputStream; import java.net.Socket; import java.io.DataOutputStream; import java.io.EOFException; import java.io.IOException; import java.io.DataInputStream;
public class ChatServer {
static ArrayList connectedClients = new ArrayList(); public static void main(String[] args) { if (args.length != 1) { //System.err.println("Usage: ChatServer "); return; }
try { int port = Integer.parseInt(args[0]);
ServerSocket serverSocket = new ServerSocket(port); while (true) { Socket client = serverSocket.accept();
ClientHandler newClient = new ClientHandler(client); connectedClients.add(newClient); newClient.start(); }
} catch (Exception e) { e.printStackTrace(); } } }
// changes right here
class ClientHandler extends Thread { Socket clientSocket; DataOutputStream output; DataInputStream input; String name = "";
public ClientHandler(Socket clientSocket) { this.clientSocket = clientSocket; }
@Override public void run() { // Initialize our input and output streams to operate off of the given client try { output = new DataOutputStream(clientSocket.getOutputStream()); input = new DataInputStream(new BufferedInputStream(clientSocket.getInputStream())); } catch (IOException e) { e.printStackTrace(); }
// Always run while the service is operational while (true) { try { // Receive String message = input.readUTF(); if (name.equals("")) { name = message; } else { System.out.println(message);
// Send to all clients for (ClientHandler client : ChatServer.connectedClients) { if (client.name.equals(name) || client.clientSocket.isClosed()) { continue; } client.output.writeUTF(name + ": " + message); } } } catch (EOFException ex) { break; } catch (IOException e) { e.printStackTrace(); break; } } try { clientSocket.close(); output.close(); input.close(); ChatServer.connectedClients.remove(this); } catch (IOException e) { e.printStackTrace(); } } }
Step by Step Solution
3.40 Rating (153 Votes )
There are 3 Steps involved in it
Step: 1
Explanation of each line of code 1 import javanetServerSocket Imports the ServerSocket class from the javanet package 2 import javanetSocket Imports the Socket class from the javanet package 3 import ...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