|
1
2
|
package pad.prac2;
|
|
3
4
|
import java.io.IOException;
|
|
5
|
public class Connection extends Thread
|
|
6
|
{
|
|
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
private MySocket socket;
private Server serv;
private boolean sleep, kill;
public Connection(Server s)
{
serv = s;
kill = false;
sleep = true;
}
public void awake()
{
synchronized(this)
{
sleep = false;
this.notify();
}
}
public void finish()
{
kill = true;
|
|
30
31
32
33
34
|
if(sleep)
{
sleep = false;
notify();
}
|
|
35
36
37
38
39
40
41
42
|
socket.close();
}
public void setSock(MySocket s)
{
socket = s;
}
|
|
43
44
45
46
47
|
public void sendMessage(String message) throws IOException
{
socket.sendMsg(message);
}
|
|
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
public void run()
{
while(!kill)
{
while(sleep)
{
try
{
synchronized(this)
{
wait();
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
if(!kill)
{
|
|
68
69
|
String str;
try
|
|
70
71
|
{
str = socket.recvMsg();
|
|
72
|
if(str.contains(" "))
|
|
73
|
{
|
|
74
|
socket.sendMsg("CHATNICKINVALID");
|
|
75
76
|
kill = true;
continue;
|
|
77
|
}
|
|
78
|
else if(serv.isOnline(str))
|
|
79
80
|
{
socket.sendMsg("CHATNICKEXIST");
|
|
81
82
83
84
85
86
87
|
kill = true;
continue;
}
else
{
socket.sendMsg("CHATOK");
serv.addToChatroom(this, str);
|
|
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
|
}
}
catch (IOException e)
{
if(!kill)
{
System.out.println("TCP: Communication with client failed while entering chatroom");
sleep = true;
serv.finishWorker(this);
}
continue;
}
while(true)
{
try
{
|
|
104
|
str = "0/disconnect";
|
|
105
|
str = socket.recvMsg();
|
|
106
|
str = str.substring(1);
|
|
107
|
if(str.equals("/disconnect"))
|
|
108
|
{
|
|
109
|
socket.sendMsg("0DISC_OK");
|
|
110
111
112
113
114
|
System.out.println(serv.getNickname(this) + " disconnected");
break;
}
else if(str.equals("/exit"))
{
|
|
115
|
socket.sendMsg("0EXIT_OK");
|
|
116
117
118
119
120
|
System.out.println(serv.getNickname(this) + " disconnected");
break;
}
else if(str.equals("/who"))
{
|
|
121
|
socket.sendMsg("0" + serv.listOnline());
|
|
122
123
124
125
|
}
else if(str.startsWith("@"))
{
try
|
|
126
|
{
|
|
127
128
|
if(!str.contains(" "))
{
|
|
129
|
serv.sendTo(this,str.substring(1),"");
|
|
130
131
132
|
}
else
{
|
|
133
|
serv.sendTo(this,str.substring(1,str.indexOf(' ')),str.substring(str.indexOf(' ')+1));
|
|
134
|
}
|
|
135
|
}
|
|
136
|
catch(ChatException cE)
|
|
137
|
{
|
|
138
|
socket.sendMsg("0"+cE.getMessage());
|
|
139
|
}
|
|
140
|
}
|
|
141
142
143
144
145
|
else
{
System.out.println("FROM " + serv.getNickname(this) + ": " + str);
serv.sendToChat(this,str);
}
|
|
146
|
}
|
|
147
|
catch(IOException ioExc)
|
|
148
|
{
|
|
149
|
System.out.println("TCP: Error writing to socket");
|
|
150
|
System.out.println(serv.getNickname(this) + " disconnected");
|
|
151
152
153
154
155
156
157
158
|
break;
}
}
sleep = true;
}
serv.finishWorker(this);
}
}
|
|
159
|
}
|