-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathServer.java
76 lines (68 loc) · 1.71 KB
/
Server.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
74
75
76
package mmn16q1;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.net.ServerSocket;
public class Server extends JFrame{
private ClientsManager cm;
private ServerSocket server;
private JTextArea ta;
private JScrollPane sp;
public Server() {
super("Server");
ta=new JTextArea();
sp=new JScrollPane(ta);
add(sp);
ta.setEditable(false);
cm=new ClientsManager(this);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
// closes all connections and close the server when trying to close the server's jframe.
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
try {
server.close();
cm.closeConnections();
}
catch (IOException e1) {
e1.printStackTrace();
}
finally {
e.getWindow().dispose();
}
}
});
setVisible(true);
setSize(300, 300);
try {
server=new ServerSocket(1234);
cm.start();
while(!server.isClosed())
handleConnection();
}
catch (IOException e) {
e.printStackTrace();
}
}
private void handleConnection() {
// We're using "--" before to make sure that the human who looks at the server log will understand that no user sent that message.
ta.append("--ServerMessage: Waiting for connection\n");
try {
cm.addConnection(server.accept());
}
catch (IOException e) {
if(server.isClosed())
return;
e.printStackTrace();
}
}
public ServerSocket getServerSocket() {
return server;
}
public JTextArea getJTextArea() {
return ta;
}
}