|
|
@ -1,65 +0,0 @@ |
|
|
|
import java.io.*; |
|
|
|
import java.net.Socket; |
|
|
|
|
|
|
|
public class ClientHandler implements Runnable { |
|
|
|
private ChatServer chatServer; |
|
|
|
private Socket connectionToClient; |
|
|
|
private String name; |
|
|
|
private BufferedReader fromClientReader; |
|
|
|
private PrintWriter toClientWriter; |
|
|
|
|
|
|
|
// Constructor for ClientHandler |
|
|
|
public ClientHandler(ChatServer chatServer, Socket connectionToClient) { |
|
|
|
this.chatServer = chatServer; |
|
|
|
this.connectionToClient = connectionToClient; |
|
|
|
name = connectionToClient.getInetAddress().getHostAddress(); // Use the client's IP address as their name for simplicity |
|
|
|
|
|
|
|
new Thread(this).start();} // Start a new thread for this client handler |
|
|
|
|
|
|
|
@Override |
|
|
|
public void run() { |
|
|
|
|
|
|
|
try { |
|
|
|
// Set up input and output streams for communication with the client |
|
|
|
fromClientReader = new BufferedReader (new InputStreamReader(connectionToClient.getInputStream())); |
|
|
|
toClientWriter = new PrintWriter (new OutputStreamWriter(connectionToClient.getOutputStream())); |
|
|
|
|
|
|
|
chatServer.broadcastMessage(name + " connected."); // Broadcast a message when the client is connected |
|
|
|
|
|
|
|
// Read messages from the client and broadcast them to all clients |
|
|
|
String message = fromClientReader.readLine(); |
|
|
|
while (message!=null) { |
|
|
|
// Broadcast the client's message to all connected clients |
|
|
|
chatServer.broadcastMessage(name + ": " + message); |
|
|
|
message = fromClientReader.readLine(); |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
catch (IOException e) { |
|
|
|
throw new RuntimeException(e); // Handle exceptions by throwing a runtime exception |
|
|
|
} |
|
|
|
finally { |
|
|
|
//chatServer.removeClient(this); |
|
|
|
chatServer.broadcastMessage(name + " disconnected."); // Broadcast a message when the client is disconnected |
|
|
|
|
|
|
|
// Close resources in the finally block |
|
|
|
if (fromClientReader != null) { |
|
|
|
try { |
|
|
|
fromClientReader.close(); |
|
|
|
} |
|
|
|
catch (IOException e){ |
|
|
|
e.printStackTrace(); |
|
|
|
} |
|
|
|
} |
|
|
|
if (toClientWriter != null) { |
|
|
|
toClientWriter.close(); |
|
|
|
} |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
//Method to send a message to the client |
|
|
|
public void sendMessage(String message) { |
|
|
|
toClientWriter.println(message); // Send the message to the client |
|
|
|
toClientWriter.flush(); // Flush the stream |
|
|
|
} |
|
|
|
} |