-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathServerConnection.java
More file actions
327 lines (271 loc) · 8.64 KB
/
ServerConnection.java
File metadata and controls
327 lines (271 loc) · 8.64 KB
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
import java.net.Socket;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class ServerConnection extends Thread
{
//Socket to the client host
private Socket socket;
//The Sopcket's InputStream
private InputStream inStream;
//The Socket's OutputStream
private OutputStream outStream;
//Channels we are currently in
private Channel channels = {new Channel("welcome","default channel")};
//Soon to be deprecated data structure
private DynamicArray<Channel> channels = new DynamicArray<Channnel>(0);
//Join the default or welcoming channel
private void joinDefaultChannel()
{
channels.append(new Channel("welcome","idk")); //FIXME: idk and how channels descriptions are going to work
}
/*The username should be unique and since our objects are we can use that as a default SET_USERNAME.
We will use this uniqeness provided by the hashcode.*/
private String username = ""+this.hashCode();
//Returns the username asociated with this user
public String getUsername()
{
return username;
}
//Set the userame
private void setUsername(String username)
{
out("User attempting to change username");
out("Username has been updated from \"" + this.username + "\" to \"" + username + "\"");
this.username = username;
}
public ServerConnection(Socket socket) {
this.socket = socket;
start();
}
//Send the given message `message` to the given channel `channel`
private void broadcastToChannel(Message message)
{
//Debugging
out("Broadcasting to channel \"" + message.getChannel().channel.getChannelName() + "\"...");
//Iterate over each connection and send each user on the given channel the new message
for(ServerConnection connection: server.connections.getArray())
{
out("Broadcasting message to \"" + connection + "\"...");
//Skip myself
if(connection != this)
{
connection.receiveMessage(message); //add to miss self (@deavmi)
}
out("Broadcast sent");
}
}
//Receive a message from a broadcast
public void receiveMessage(Message message)
{
//Write it to the user host
IO.sendCommand("RECEIVED_MESSAGE");
//Tell the user the channel the message originated from
IO.sendCommand(message.getChannel().getChannelName());
//Provide the actual message text to the user
IO.sendCommand(message.getMessageText());
}
//Join a channel
private void joinChannel(Channel channel)
{
out("Joining channel \"" + channel.getChannelName() + "\"");
this.channel = channel;
out("Joined channel \"" + channel.getChannelName() + "\"");
}
//Whether the user is joined to a channel or not
public boolean isJoinedChannel()
{
return channels.length != 0;
}
//Send a message `message` to the channel specified
public void sendMessage(Message message)
{
out("message : \"" + message+ "\"");
//Broadcast the message to the given channel
broadcastToChannel(message);
//we good?
IO.sendCommand(outStream, "MESSAGE_SENT");
}
//Lists all the channels on this server
public Channel[] listChannels()
{
return channels.getArray();
}
//Leave channel `channel`
public void leaveChannel(Channel channel)
{
//Debugging
out("Leaving channel \"" + channel.getChannelName() + "\"");
//Send a message to the current channel when leaving
//WP: @assigned to deavmi
//Find the channel to remove
int channelPos = 0;
for(int i = 0; i < channels.getArray().length; i++)
{
if(channels.getArray()[i].getChannelName().equals(channel.getChannelName()))
{
channelPos = i;
break;
}
}
//Remove the channel
channels.remove(channelPos);
//Debugging
out("Left channel \"" + channel.getChannelName() + "\"");
}
public void setupStreams()
{
out("Setting up streams...");
try
{
out("Setting up input stream...");
inStream = sock.getInputStream();
out("Input stream has been setup.");
out("Setting up output stream...");
outStream = sock.getOutputStream();
out("Output stream has been setup.");
}
catch (IOException err)
{
out("Error setting up stream: " + err.getMessage());
}
out("Streams setup.");
}
//Checks whether you are joined to the channel `channel` or not
public boolean isJoinedToChannel(Channel channelToLeave)
{
for(Channel channel: channnels.getArray())
{
if(channel.getChannelName().equals(channelToLeave.getChannelName()))
{
return true;
}
}
return false;
}
//Setup routines
public void setup()
{
//Debugging
out("Setup is taking place...");
out("Setting up streams...")
// Setup the input and output streams
setupStreams();
//Debugging
out("Setting up streams... [done]");
out("Joining default channel...");
//Join the default channel (a.k.a. the `welcome` channel)
joinDefaultChannel();
//Debugging
out("Joining default channel... [done]");
out("Setup is taking place... [done]");
}
//This thread's main routine
public void run()
{
//TODO: Add a welcome statement
//Announce server version to the client
//IO.sendCommand(outStream, suixd.VERSION);
out("New Connection object created");
//Run setup routines
setup();
String command = "";
boolean running = true;
while (running)
{
// Read from the client
command = IO.readCommand(inStream);
//If there was an error whilst reading from the stream
if(command == null)
{
out("There was an error with the client, terminating...");
running = false;
continue;
}
//Else, we continue interpreting the commands
else
{
out("command recieved: \"" + command + "\"");
//If the command is to set the currently logged in user's username
if(command.equals("SET_USERNAME"))
{
String newUsername = IO.readCommand(inStream);
setUsername(newUsername);
}
else if(command.equals("GET_USERNAME"))
{
IO.sendCommand(outStream, username);
}
//If the command is to join a channel
else if(command.equals("JOIN_CHANNEL"))
{
//Set the current channel (and leave the other WIP)
String userRequestedChannel = IO.readCommand(inStream);
Channel channelToJoin = new Channel(userRequestedChannel, "tbd"); //FIXME: assigned to @deavmi
//Join the requested channel
joinChannel(channelToJoin);
}
else if(command.equals("LEAVE_CHANNEL"))
{
//Get the channel the user is requesting to leave
Channel channel = new Channel(IO.readCommand(inStream),"WIP");
//First check if it is possible
boolean isPossible = isJoinedToChannel(channel)
if(isPossible)
{
//Leave the channel
leaveChannel(new Channel(channelToLeave,"idk"));
//Send a response saying the leave was successful
IO.sendCommand(outStream, "LEAVE_SUCCESS");
}
else
{
//Send a response saying the leave was unsucccessful
IO.sendCommand(outStream, "LEAVE_ERROR");
}
}
else if(command.equals("SEND_MESSAGE"))
{
//Get the channel of which to send the message to
String channelForMessage = IO.readCommand(inStream);
//Get the message's text
String messageText = IO.readCommand(inStream);
out("Ello naai: "+messageText);
Channel channel = new Channel(channelForMessage, "wip");
Message message = new Message(channel, messageText);
sendMessage(message);
}
//Get the server's version number
else if(command.equals("VERSION"))
{
out("Sending version number to client...");
IO.sendCommand(outStream, suixd.VERSION);
out("Version number sent.");
}
//List all the channels the user is joined to
else if(command.equals("LIST_CHANNELS"))
{
//Send the amount of channels to the user so he knows how many of
//my messages are channels
IO.sendCommand(outStream, ""+channels.getArray().length);
//Now send the channel names to him
for(Channel channel: channels.getArray())
{
IO.sendCommand(outStream, channel.getChannelName());
}
}
else
{
out("Invalid command \""+command + "\"");
}
}
}
out("Connection object thread ending");
}
//Output text to the `stdout` file descriptor (a.k.a. the terminal screen) with a useful debugging information
//Output with pretty print and this module's name (FIXME: @deavmi)
private void out(String message)
{
PrettyPrint.out("Connection (" +username +")","[LA: " + sock.getLocalAddress() + ", LP: " + sock.getLocalPort() + ", RA: " + sock.getInetAddress() + ", RP: " + sock.getPort() + "]: " + message);
}
}