-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path#ConnectionServer.java#
98 lines (82 loc) · 2.51 KB
/
#ConnectionServer.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
class ConnectionServer implements Runnable {
// some constants
public static final int WAIT_AUTH = 0;
public static final int AUTH_DONE = 1;
public static final String WAIT_AUTH_MSG = "Registration Number pls!\n";
public static final String AUTH_DONE_MSG = "You are authorised to post\n";
public static final String MSG_POSTED = "Your message posted\n";
// per connection variables
private Socket mySocket; // connection socket per thread
private int currentState;
private String clientName;
private MainServer mainServer;
int count;
public ConnectionServer(MainServer mainServer) {
this.mySocket = null; // we will set this later
this.currentState = WAIT_AUTH;
this.clientName = null;
this.mainServer = mainServer;
this.count=0;
// who created me. He should give some interface
}
public boolean handleConnection(Socket socket) {
this.mySocket = socket;
Thread newThread = new Thread(this);
newThread.start();
return true;
}
public void run() { // can not use "throws .." interface is different
BufferedReader in=null;
PrintWriter out=null;
try {
in = new
BufferedReader(new InputStreamReader(mySocket.getInputStream()));
out = new
PrintWriter(new OutputStreamWriter(mySocket.getOutputStream()));
String line, outline;
for(line = in.readLine();
line != null && !line.equals("quit");
line = in.readLine()) {
switch(currentState) {
case WAIT_AUTH:
// we are waiting for login name
// e number should be the line
if(mainServer.isAuthorized(line)) {
currentState = AUTH_DONE;
clientName = mainServer.getName(line);
outline = AUTH_DONE_MSG;
}
else {
outline = WAIT_AUTH_MSG;
}
break;
/*****************************/
case AUTH_DONE:
mainServer.postMSG(this.clientName + " Says: " + line);
++this.count;
if(this.count>5) return;
outline = MSG_POSTED;
break;
default:
System.out.println("Undefined state");
return;
} // case
out.print(outline); // Send the said message
out.flush(); // flush to network
} // for
// close everything
out.close();
in.close();
this.mySocket.close();
} // try
catch (IOException e) {
System.out.println(e);
}
}
}