-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServerWriter.java
More file actions
88 lines (81 loc) · 3.1 KB
/
ServerWriter.java
File metadata and controls
88 lines (81 loc) · 3.1 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
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.util.Arrays;
import java.util.concurrent.BlockingQueue;
public class ServerWriter implements Runnable{
private Socket s;
private final BlockingQueue<byte []> localQueue;
private final BlockingQueue<byte[]> storageQueue;
private ServerProcessor processor;
private volatile boolean running = true;
public ServerWriter(Socket s, BlockingQueue<byte[]> localQueue, ServerProcessor Servproc, BlockingQueue<byte[]> storageQueue) {
this.s = s;
this.localQueue = localQueue;
this.processor = Servproc;
this.processor.setWriter(this);
this.storageQueue = storageQueue;
}
private synchronized void analyzeStorage(OutputStream out, String client_id){
byte[] message = storageQueue.peek();
byte[] idLength = Arrays.copyOfRange(message, 0, 2);
int length = ((idLength[0] & 0xFF) << 8) | (idLength[1] & 0xFF);
byte[] identifierByte = Arrays.copyOfRange(message, 2, 2 + length);
String client_identifier = "";
try{
client_identifier = new String(identifierByte ,"UTF8");
}catch(UnsupportedEncodingException e){
System.out.println("Something went wrong");
}
if(client_identifier.equals(client_id)){
System.out.println("VICTORYYYYYYYYYYYYYYYYYYYYY");
byte[] a = Arrays.copyOfRange(message, 2 + length, message.length);
// for(int i=0; i<a.length;i++){
// System.out.println(String.format("%8s", Integer.toBinaryString(a[i] & 0xFF)).replace(' ', '0'));
// }
try {
out.write(a);
out.flush();
} catch(IOException e){
System.out.println("Something was interrupted");
}
storageQueue.remove();
}
}
@Override
public void run(){
String client_id = processor.getClientId();
while(running) {
try{
OutputStream out = s.getOutputStream();
// do something
// test
while(true){
if(!localQueue.isEmpty()){
try{
byte[] a = localQueue.take();
out.write(a);
out.flush();
} catch(InterruptedException e){
System.out.println("Interrupted");
}
}
if(!storageQueue.isEmpty()){
client_id = processor.getClientId();
analyzeStorage(out, client_id);
}
}
// s.close();
} catch (IOException a){
System.out.println("ServerWorker died");
}
}
}
/**
* Stops the thread
*/
public void terminate() {
running = false;
}
}