-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatServer.java
More file actions
executable file
·292 lines (244 loc) · 9.68 KB
/
Copy pathChatServer.java
File metadata and controls
executable file
·292 lines (244 loc) · 9.68 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
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.io.IOException;
import java.net.Socket;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.net.ServerSocket;
/* ChatServer class listens on the port for incoming requests.
It runs a separate thread for each client maintained as an array of threads.
It keeps count of the connected current clients.
*/
public class ChatServer {
// The server socket.
private static ServerSocket serverSocket = null;
// The client socket.
private static Socket clientSocket = null;
// Array of threads
private static final clientThread[] threads = new clientThread[100];
public static void main(String args[]) {
int portNumber = 2222;
if (args.length < 1) {
System.out
.println("Server started on portnumber: " + portNumber);
} else {
portNumber = Integer.valueOf(args[0]).intValue();
}
try {
serverSocket = new ServerSocket(portNumber);
File file = new File("server");
file.mkdir();
} catch (IOException e) {
System.out.println(e);
}
/*
* Create a client socket for each connection, pass it to a new client
* thread and update count of current clients.
*/
int currClientsCount = -1;
while (true) {
try {
clientSocket = serverSocket.accept();
currClientsCount++;
System.out.println("New Client added. Current client count = "+currClientsCount);
(threads[currClientsCount] = new clientThread(clientSocket, threads, currClientsCount)).start();
for(int i=0; i<currClientsCount;i++)
{
threads[i].updateClientCount(currClientsCount);
}
} catch (IOException e) {
System.out.println(e);
}
}
}
}
/*
* The client thread opens the input and the output streams for a particular client.
* It handles the commands send from the client for broadcast/unicast and blockcast
* of messages and files.
*/
class clientThread extends Thread {
private DataInputStream is = null;
private DataOutputStream dos = null;
private PrintStream os = null;
private Socket clientSocket = null;
private final clientThread[] threads;
private String clientName = "";
private int currClientsCount = 0;
public clientThread(Socket clientSocket, clientThread[] threads, int currClientsCount) {
this.clientSocket = clientSocket;
this.threads = threads;
this.currClientsCount= currClientsCount;
}
public void updateClientCount(int currClientsCount)
{
this.currClientsCount = currClientsCount;
}
public void saveFile(Socket clientSock,DataOutputStream dos, String sender, String filename, int filesize) throws IOException {
DataInputStream dis = new DataInputStream(clientSock.getInputStream());
FileOutputStream fos = new FileOutputStream(System.getProperty("user.dir")+"/server/"+"servercopy"+filename);
byte[] buffer = new byte[4096];
int read = 0;
int totalRead = 0;
int remaining = filesize;
while((read = dis.read(buffer, 0, Math.min(buffer.length, remaining))) > 0) {
totalRead += read;
remaining -= read;
fos.write(buffer, 0, read);
}
fos.close();
}
public void sendFile(DataOutputStream dos,String file) throws IOException {
FileInputStream fis = new FileInputStream(System.getProperty("user.dir")+"/server/"+"servercopy"+file);
int filesize = (int) fis.getChannel().size();
byte[] buffer = new byte[filesize];
fis.read(buffer);
dos.write(buffer);
fis.close();
}
public boolean isValidCommand(String name)
{
for(int i=0; i <= currClientsCount;i++)
{
if(threads[i].clientName.equals(name))
{
return true;
}
}
return false;
}
public boolean isFileExist(String filename)
{
File varTmpDir = new File(filename);
boolean exists = varTmpDir.exists();
return exists;
}
public void run() {
clientThread[] threads = this.threads;
try {
is = new DataInputStream(clientSocket.getInputStream());
dos=new DataOutputStream(clientSocket.getOutputStream());
os = new PrintStream(clientSocket.getOutputStream());
os.println("Enter a one word username:");
String name = is.readLine();
this.clientName=name;
os.println("Welcome " + name
+ "!\n Enter commands as follows:\n"
+ "To broadcast a messagae : broadcast msg <text> \n"
+ "To unicast a message: unicast msg <text> username \n"
+ "to blockcast a message: blockcast msg <text> username \n"
+ "To broadcast a file: broadcast file <filename> \n"
+ "To unicast a file: unicast file <filename> username \n"
+ "To leave: /quit");
for (int i = 0; i <= currClientsCount; i++) {
if (threads[i] != null && threads[i] != this) {
threads[i].os.println("*** username: " + this.clientName
+ " entered the chat room ***");
}
}
// Create a directory for the client
File file = new File(this.clientName);
file.mkdir();
while (true) {
String line = is.readLine();
if(line == null){
break;
}
else if (line.startsWith("/quit")) {
break;
}
String[] splitted= line.split("\\s+");
String clientName= null;
String msg="";
for(int k=2;k<splitted.length-1;k++){
msg+=splitted[k]+" ";
}
if (line.startsWith("blockcast msg") && isValidCommand(splitted[splitted.length-1])) {
clientName= splitted[splitted.length-1];
for (int j = 0; j <= currClientsCount; j++) {
if (threads[j]!=null && !threads[j].clientName.equals(clientName)) {
threads[j].os.println("@" + this.clientName + ":"+msg);
}
}
}
else if (line.startsWith("unicast msg")&& isValidCommand(splitted[splitted.length-1])) {
clientName= splitted[splitted.length-1];
for (int j = 0; j <= currClientsCount; j++) {
if (threads[j]!=null && threads[j].clientName.equals(clientName)) {
threads[j].os.println("@" + this.clientName + ":" + msg);
}
}
this.os.println("@"+ this.clientName+":" + msg);
}
else if (line.startsWith("broadcast msg")) {
for (int i = 0; i <= currClientsCount; i++) {
if (threads[i] != null) {
threads[i].os.println("@" + this.clientName + ":" + msg+splitted[splitted.length-1]);
}
}
}
else if (line.startsWith("broadcast file") && isFileExist(splitted[2])) {
String filename = splitted[2];
int filesize= Integer.parseInt(splitted[3]);
saveFile(clientSocket,threads[0].dos, this.clientName, filename, filesize);
for (int i = 0; i <= currClientsCount; i++) {
if (threads[i] != null && !threads[i].clientName.equals(this.clientName)) {
threads[i].os.println("download "+threads[i].clientName+" "+ filename +" "+this.clientName + " "+ filesize);
sendFile(threads[i].dos,splitted[2]);
System.out.println("*** File "+ filename+ " sent to "+ threads[i].clientName+" ***");
}
}
this.os.println("*** File sent successfully ***");
//Delete temporary file in server directory
Path path = FileSystems.getDefault().getPath(System.getProperty("user.dir")+"/server", "servercopy"+filename);
Files.deleteIfExists(path);
}
else if (line.startsWith("unicast file") && isValidCommand(splitted[3]) && isFileExist(splitted[2])) {
String filename = splitted[2];
int filesize= Integer.parseInt(splitted[4]);
saveFile(clientSocket,threads[0].dos, this.clientName, filename, filesize);
for (int i = 0; i <= currClientsCount; i++) {
if (threads[i] != null && threads[i].clientName.equals(splitted[3])) {
threads[i].os.println("download "+threads[i].clientName+" "+ filename+" "+this.clientName +" "+ filesize);
sendFile(threads[i].dos,splitted[2]);
System.out.println("*** File "+ filename+ " sent to "+ threads[i].clientName+" ***");
}
}
this.os.println("*** File sent successfully ***");
//Delete temporary file in server directory
Path path = FileSystems.getDefault().getPath(System.getProperty("user.dir")+"/server", "servercopy"+filename);
Files.deleteIfExists(path);
}
else{
this.os.println("Invalid command line.");
}
}
/*
* Handle connection close and clean up.
*/
for (int i = 0; i <= currClientsCount; i++) {
if (threads[i] != null && threads[i] != this) {
threads[i].os.println("*** User " + name + " has left the chat room !!! ***");
}
}
os.println("*** Bye " + name + " ***");
for (int i = 0; i <= currClientsCount; i++) {
if (threads[i] == this) {
threads[i] = null;
}
}
/*
* Close the output stream, close the input stream, close the socket.
*/
is.close();
os.close();
clientSocket.close();
} catch (IOException e) {
}
}
}