-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatServer.java
More file actions
83 lines (67 loc) · 2.53 KB
/
Copy pathChatServer.java
File metadata and controls
83 lines (67 loc) · 2.53 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
package chat.server;
import chat.network.TCPConnection;
import chat.network.TCPConnectionListener;
import javafx.application.Application;
import javafx.stage.Stage;
import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.ArrayList;
public class ChatServer extends Application implements TCPConnectionListener {
public static void main(String[] args) {
new ChatServer();
//launch(args);
}
private final ArrayList<TCPConnection> connections = new ArrayList<>();
private ChatServer(){
/**
JFrame j = new JFrame();
JPanel p = new JPanel(new BorderLayout());
JLabel l = new JLabel("Server is running");
p.add(l, "Center");
j.setSize(200,100);
j.setContentPane(p);
j.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
j.setVisible(true);
*/
System.out.println("Server running...");
try(ServerSocket serverSocket = new ServerSocket(8189)) {
while (true){
try {
new TCPConnection(this,serverSocket.accept());
}catch (IOException e){
System.out.println("TCPConnection exception: " + e);
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public void start(Stage primaryStage) throws Exception {
}
@Override
public void onConnectionReady(TCPConnection tcpConnection) {
connections.add(tcpConnection);
sendToAllConnections("Client connected: " + tcpConnection);
}
@Override
public void onReceiveString(TCPConnection tcpConnection, String value) {
sendToAllConnections(value);
}
@Override
public void onDisconnect(TCPConnection tcpConnection) {
connections.remove(tcpConnection);
sendToAllConnections("Client disconnected: " + tcpConnection);
}
@Override
public void onException(TCPConnection tcpConnection, Exception e) {
System.out.println("TCPConnection exception: " + e);
}
private void sendToAllConnections(String value){
System.out.println(value);
for (TCPConnection connection : connections)
connection.sendString(value);
}
}