-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConnection.java
108 lines (100 loc) · 2.76 KB
/
Connection.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
98
99
100
101
102
103
104
105
106
107
108
package mmn16q1;
import java.net.Socket;
import java.util.Formatter;
import java.util.Scanner;
import java.io.IOException;
public class Connection extends Thread{
private Socket connection;
private Formatter output;
private Scanner input;
private String username;
private ClientsManager cm;
private String in; // holds the input received from the scanner.
public Connection(Socket s, ClientsManager clientsManager) {
connection=s;
this.cm=clientsManager;
try {
input=new Scanner(s.getInputStream());
output=new Formatter(s.getOutputStream());
}
catch (IOException e) {
e.printStackTrace();
}
}
public Scanner getInput() {
return input;
}
public Formatter getOutput() {
return output;
}
public String getUsername() {
return username;
}
@Override
public void run() {
in=input.nextLine(); // getting username from the client
if(in.equals("No username entered")) {
closeConnection();
cm.removeFromConnections(this);
return;
}
cm.unLock.lock();
while(cm.getUn()!=null) // There's already a user that's in the middle of the connecting process, waiting for our turn.
try {
cm.unCon.await();
}
catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
cm.setLastConnection(this);
username=cm.UserNameChecker(in);
output.format("%s\n",username);
output.format("%d\n",cm.getConnectionSize());
if(cm.getConnectionSize()>1)
output.format(cm.getConnectedUsernames());
output.flush();
cm.setUn(username);
cm.unLock.unlock();
//we can implement msg-seen feature if we want. just check in client side if the gui got focused since the msg sent. and check who focused the gui or something.
while (true) {
try {
if(input.hasNextLine()&&!(in=input.nextLine()).equals("Logout")) {
cm.msgLock.lock();
while(cm.getMsg()!=null)// There's already a message that needs to be announce to all the connections.
try {
cm.msgCon.await();
}
catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
cm.setMsg(in);
cm.msgLock.unlock();
}
}catch(java.lang.IllegalStateException e) {
if(cm.getServerSocket().isClosed())
return;
e.printStackTrace();
}
if(in.equals("Logout")) {
closeConnection();
cm.removeFromConnections(this);
break;
}
}
}
void closeConnection() {
try {
output.format("Shutdown\n");
output.flush();
output.close();
input.close();
if(!connection.isClosed())//The connection will be closed only if the server shutdown manually
connection.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}