-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatServer.java
More file actions
88 lines (77 loc) · 2.41 KB
/
ChatServer.java
File metadata and controls
88 lines (77 loc) · 2.41 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashSet;
import java.util.Set;
/*
This is the chat server program.
*/
public class ChatServer {
private int port;
private Set<String> userNames = new HashSet<>();
private Set<UserThread> userThreads = new HashSet<>();
public ChatServer(int port) {
this.port = port;
}
public void execute() {
try (ServerSocket serverSocket = new ServerSocket(port)) {
System.out.println("Chat Server is listening on port " + port);
while(true) {
Socket socket = serverSocket.accept();
System.out.println("New user connected");
UserThread newUser = new UserThread(socket, this);
userThreads.add(newUser);
newUser.start();
}
} catch (IOException ex) {
System.out.println("Error in the server: " + ex.getMessage());
ex.printStackTrace();
}
}
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Syntax: java ChatServer <port-number>");
System.exit(0);
}
int port = Integer.parseInt(args[0]);
ChatServer server = new ChatServer(port);
server.execute();
}
/*
Delivers a message from one user to others (broadcasting)
*/
void broadcast (String message, UserThread excludeUser) {
for (UserThread aUser : userThreads
) {
if (!aUser.equals(excludeUser)) {
aUser.sendMessage(message); // sends message back to the client
}
}
}
/*
Stores username of the newly connected client.
*/
void addUserName(String userName) {
userNames.add(userName);
}
/*
When a client is disconnected, removes the associated username and userThread
*/
void removeUser (String userName, UserThread aUser) {
boolean removed = userNames.remove(userName);
if (removed) {
userThreads.remove(aUser);
System.out.println("The user " + userName + " quit.");
}
}
Set<String> getUserNames() {
return this.userNames;
}
/*
Returns true if there are others users connected (not count the currently
connected user)
*/
boolean hasUsers() {
return !this.userNames.isEmpty();
}
}