-
Notifications
You must be signed in to change notification settings - Fork 2
/
ClientThread.java
218 lines (182 loc) · 6.69 KB
/
ClientThread.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.charset.*;
import java.util.*;
import java.time.*;
import java.time.format.*;
public class ClientThread extends Thread {
Socket socket;
DataInputStream dataIn;
DataOutputStream dataOut;
int usernameIndex;
int clientIndex;
byte[] out;
DateTimeFormatter formatter =
DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
.withLocale(Locale.UK)
.withZone(ZoneId.systemDefault());
byte command;
short msgLen;
byte[] msgBytes;
String msgData;
Instant timestamp;
public ClientThread(Socket socket) throws IOException, FileNotFoundException
{
this.socket = socket;
dataIn = new DataInputStream(socket.getInputStream());
dataOut = new DataOutputStream(socket.getOutputStream());
Server.addLog("Connection accepted. IP Address: " + socket.getRemoteSocketAddress() + " Port: " + socket.getPort());
}
public void run()
{
try {
while(true) {
command = dataIn.readByte();
if(command != (byte)3)
{
msgLen = dataIn.readShort();
msgBytes = new byte[3 + Integer.valueOf(msgLen)];
dataIn.read(msgBytes);
msgData = asciiToString(msgBytes);
}
switch((int)command)
{
case 0: // join
joinServer(msgData);
break;
case 1: // leave
leaveServer(msgData);
return;
case 2: // talk
System.out.println("Sent a message");
talk("["+Server.usernames.get(usernameIndex)+"] "+ msgData);
break;
case 3: // list
list();
break;
case 4: // direct
direct(msgData);
case 5: // error / default
default: // default
error();
}
}
}
catch (IOException e) {
System.err.println("Exception in Client thread: " + e);
}
}
void joinServer(String message) throws IOException {
boolean taken = false;
String workingCommands = "Available Commands: \n join \n leave \n talk \n list \n direct \n error \n";
for (int i = 0; i < Server.clients.size(); i++) {
if(Server.usernames.contains(message))
{
command = 1;
out = new byte[]{command};
dataOut.write(out);
Server.addLog("Requested username: " + message + ". Rejected - already in use.");
taken = true;
break;
}
}
if (!taken){
//System.out.println("username: " + message);
usernameIndex = Server.usernames.size();
Server.usernames.add(message);
command = 0;
out = new byte[]{command};
dataOut.write(out);
Server.addLog("Requested username: " + message + ". Accepted.");
//System.out.println("index: " + usernameIndex);
//System.out.println(Server.usernames.get(usernameIndex));
String talkmsg = "- " + Server.usernames.get(usernameIndex) + " connected -";
timestamp = Instant.now();
Server.addLog(talkmsg + formatter.format(timestamp));
talk(talkmsg);
sendMessage((byte)2,(short) workingCommands.length(), workingCommands);
}
}
public void leaveServer(String message) throws UnsupportedEncodingException
{
talk("- "+Server.usernames.get(usernameIndex)+" disconnected -");
timestamp = Instant.now();
Server.addLog("- "+Server.usernames.get(usernameIndex)+" disconnected - " + formatter.format(timestamp));
Server.clientNumberToRemove.add(usernameIndex);
return;
}
public void talk(String message) throws UnsupportedEncodingException
{
byte command = (byte)2;
byte[] msgData = stringToAscii(message);
short msgLen = (short) message.length();
Server.addLog(message);
Server.sendall(command, msgLen, msgData);
}
public void list(){
StringBuilder userList = new StringBuilder();
//userList.append("Connected users: \n");
for (int i = 0; i < Server.usernames.size(); i++) {
userList.append(" \n" + Server.usernames.get(i));
}
msgLen = (short) userList.toString().length();
sendMessage(command ,msgLen ,userList.toString());
}
public void direct(String message){
String messageArray[] = message.split(" ");
String sendTo = messageArray[0];
message = message.replace(sendTo+" ", "");
int userIndex = 0;
for (int i = 0; i < Server.usernames.size(); i++) {
if (sendTo.equals(Server.usernames.get(i))){
userIndex = i;
break;
}
}
msgLen = (short) message.length();
Server.clients.get(userIndex).sendMessage(command, msgLen, message);
}
public void error(){
String message = "[Error] Invalid command";
byte error = 5;
msgLen = (short) message.length();
sendMessage(error, msgLen, message);
}
public boolean sendMessage(byte command, short msgLen, String message){
byte[] msg;
ByteBuffer bytePkg;
try {
//Three bytes for header, then however many needed for the actual data
bytePkg = ByteBuffer.allocate(3 + msgLen);
//Pack the information: both header and data
bytePkg.put(command);
bytePkg.putShort(msgLen);
msg = stringToAscii(message);
bytePkg.put(msg);
//Send to the server
dataOut.write(bytePkg.array());
} catch (Exception e){
System.err.println(e);
return false;
}
return true;
}
public String asciiToString(byte[] PAB) {
if (PAB == null || PAB.length == 0)
return "";
char[] arrayOfChar = new char[PAB.length];
for (byte b = 0; b < PAB.length; b++) {
arrayOfChar[b] = (char)PAB[b];
}
return new String(arrayOfChar);
}
public byte[] stringToAscii(String paramString) throws UnsupportedEncodingException {
if (paramString != null){
return paramString.getBytes(StandardCharsets.US_ASCII);
}
else {
return new byte[1];
}
}
}