-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServer.java
More file actions
91 lines (80 loc) · 2.24 KB
/
Server.java
File metadata and controls
91 lines (80 loc) · 2.24 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
89
90
91
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class Server {
ArrayList<Socket> alSocket;
ServerSocket ss;
// ServeurFrame serv;
Server(int port){
this.ss = null;
this.alSocket = new ArrayList<>();
try {
ss = new ServerSocket(port);
} catch (Exception e1) {
e1.printStackTrace();
}
// this.serv = new ServeurFrame();
Thread acceptClient = new Thread(new Runnable() {
@Override
public void run() {
acceptClient();
}
});
acceptClient.start();
}
private void acceptClient() {
while(true) {
try {
Socket s = this.ss.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
this.alSocket.add(s);
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
out.println("Welcome");
out.flush();
new Thread(new Runnable() {
@Override
public void run() {
readStream(alSocket.size(), in, s);
}
}).start();
// this.serv.add("New client, number "+this.clientList.size());
} catch (IOException e) {
System.err.println("Cant add cilent");
e.printStackTrace();
}
}
}
private void readStream(int nb, BufferedReader in, Socket s) {
String text = "";
while(s != null && s.isConnected() && !text.equals("null")) {
try{
text = in.readLine();
// this.serv.add("["+nb+"] : "+text);
this.sendMsgToAllExcept(nb, text);
}catch(Exception e){
System.err.println("Socket Exception in read stream");
e.printStackTrace();
}
}
System.out.println("Client is disconnected");
}
private void sendMsgToAllExcept(int nb, String text) {
for(int i=1; i<=this.alSocket.size(); i++) {
if(this.alSocket.get(i-1).isConnected()) {
try {
PrintWriter out = new PrintWriter(this.alSocket.get(i-1).getOutputStream(), true);
out.println("["+(i==nb ? "You" : nb)+"] : "+text);
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}else {
System.out.println("Just noticed that "+i+" is disconnected");
}
}
}
}