-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTyrantMap.java
More file actions
70 lines (58 loc) · 1.95 KB
/
TyrantMap.java
File metadata and controls
70 lines (58 loc) · 1.95 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
package com.example.cleancoder.tdd.tyrant;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class TyrantMap {
public static final int OPERATION_PREFIX = 0xC8;
public static final int OPERATION_PUT = 0x10;
public static final int OPERATION_GET = 0x30;
private Socket socket;
private DataOutputStream writer;
private DataInputStream reader;
public void put(String key, String value) throws IOException {
writeHeader(OPERATION_PUT);
writeKeyValue(key, value);
verifyStatus();
}
public void open() throws IOException {
socket = new Socket("localhost", 1978);
writer = new DataOutputStream(socket.getOutputStream());
reader = new DataInputStream(socket.getInputStream());
}
public byte[] get(String key) throws IOException {
writeHeader(OPERATION_GET);
writeKey(key);
verifyStatus();
return readResults();
}
public void close() throws IOException {
reader.close();
writer.close();
socket.close();
}
private void writeKey(String key) throws IOException {
writer.writeInt(key.length());
writer.write(key.getBytes());
}
private void writeHeader(int operationCode) throws IOException {
writer.write(OPERATION_PREFIX);
writer.write(operationCode);
}
private void writeKeyValue(String key, String value) throws IOException {
writer.writeInt(key.length());
writer.writeInt(value.length());
writer.write(key.getBytes());
writer.write(value.getBytes());
}
private void verifyStatus() throws IOException {
int status = reader.read();
assert status == 0;
}
private byte[] readResults() throws IOException {
int length = reader.readInt();
byte[] results = new byte[length];
reader.read(results);
return results;
}
}