-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTCPChatClient.java
76 lines (62 loc) · 2.32 KB
/
TCPChatClient.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.programs.www;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.time.LocalDateTime;
/*
@author: prachi.shah
@date: 8-27-2024
*/
// TCPChatClient class to manage individual client connections
public class TCPChatClient implements Runnable {
private final Socket socket;
private PrintWriter out;
public TCPChatClient(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
// Ask the client for their username
out.println("Enter your username: ");
String username = in.readLine();
// Add a client to the list
TCPChatServer.addClient(this);
// Broadcast that a new user has joined
TCPChatServer.broadcastMessage(LocalDateTime.now() + ": @" + username + " has joined the chat!");
String message;
while ((message = in.readLine()) != null) {
if (message.equalsIgnoreCase("BYE!")) {
break;
}
System.out.println(LocalDateTime.now() + ": @" + username + ": " + message);
// Broadcast a message with username and timestamp
TCPChatServer.broadcastMessage(LocalDateTime.now() + ": @" + username + ": " + message);
}
// Notify others that the user is leaving
TCPChatServer.broadcastMessage(LocalDateTime.now() + ": @" + username + " has left the chat.");
} catch (IOException e) {
System.out.println("IOException occurred: " + e.getMessage());
} finally {
// Clean up and close connection
closeConnection();
}
}
public void sendMessage(String message) {
out.println(message);
}
public void closeConnection() {
try {
if (socket != null && !socket.isClosed()) {
socket.close();
}
} catch (IOException e) {
System.out.println("IOException occurred: " + e.getMessage());
}
TCPChatServer.removeClient(this);
}
}