forked from hamzaouaddafe/AnnonceManager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ServerThread.java
73 lines (61 loc) · 2.26 KB
/
ServerThread.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
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
public class ServerThread extends Thread {
private ServerTCP serverTCP = null;
private Socket client = null;
private BufferedReader bufferedReader;
private PrintStream printStream;
private int id;
private String message;
private Action action;
private boolean flag = true;
public ServerThread(Socket client, int count, ServerTCP serverTCP) {
try {
this.action = new Action(this);
this.client = client;
this.serverTCP = serverTCP;
this.id = count;
System.out.println(
"## Connection ("
+ id
+ ") established with client from "
+ client.getLocalAddress()
+ " : "
+ client.getPort());
} catch (Exception e) {
System.err.println("Error in ServerThread() : " + e.getMessage());
}
}
public void run() {
try {
while (serverTCP.getClientCount() > 0) {
bufferedReader = new BufferedReader(new InputStreamReader(client.getInputStream()));
printStream = new PrintStream(client.getOutputStream());
message = bufferedReader.readLine();
if (message != null) {
System.out.println("Client(" + id + ") : " + message);
}
if ("bye".equalsIgnoreCase(message)) {
this.serverTCP.setClientCount(this.serverTCP.getClientCount() - 1);
System.out.println("Connection ended by server");
} else {
message = action.handleRequest(message);
}
printStream.println(message);
flag = false;
}
bufferedReader.close();
client.close();
printStream.close();
System.out.println("Server cleaning up.");
System.exit(0);
} catch (Exception ex) {
System.out.println("Error in run() : " + ex.getMessage());
}
}
public boolean isFlag() {
return flag;
}
}