-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServerInit.java
More file actions
84 lines (68 loc) · 2.73 KB
/
ServerInit.java
File metadata and controls
84 lines (68 loc) · 2.73 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
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
public class ServerInit {
private boolean status = false;
HashMap<String, LinkedBlockingQueue<String>> blockingQueues = new HashMap<>();
/**
**/
public void ProducerInputThread(InputStream inputStream){ // Need a way to exit out of while loop. Maybe program a way for the client to exit
try(BufferedReader in = new BufferedReader(new InputStreamReader(inputStream))){
while(status){
String[] message = null;
if (in.ready()){
message = (in.readLine()).split(" ", 1);
for (String client : blockingQueues.keySet()){
if (message[0].equals(client)){
blockingQueues.get(client).put(message[2]);
}
}
}
}
} catch(IOException | InterruptedException e){
System.out.println(e.getMessage());
}
}
/**
**/
public void ConsumerOutputThread(OutputStream outputStream, String key){
try(PrintWriter out = new PrintWriter(new OutputStreamWriter(outputStream))){
LinkedBlockingQueue<String> queue = blockingQueues.get(key);
while(status){
String message = (String) queue.take();
out.println(message);
}
} catch(InterruptedException f){
System.out.println(f.getMessage());
}
};
public void run(){
ArrayList<Socket> clientsList = new ArrayList<>();
ExecutorService inputThreadPool = Executors.newFixedThreadPool(3);
ExecutorService outputThreadPool = Executors.newFixedThreadPool(3);
status = true;
try{
ServerSocket serverSocket = new ServerSocket(8080);
Socket client = null;
while(status){
client = serverSocket.accept();
blockingQueues.put(("Client" + blockingQueues.size()), new LinkedBlockingQueue<>());
InputStream inputStream = client.getInputStream();
OutputStream outputStream = client.getOutputStream();
inputThreadPool.submit(() -> {
ProducerInputThread(inputStream);
});
outputThreadPool.submit( () -> {
ConsumerOutputThread(outputStream, ("Client" + blockingQueues.size()));
});
}
} catch(IOException e){
System.out.println(e.getMessage());
}
}
}