-
Notifications
You must be signed in to change notification settings - Fork 32
/
Memg.java
96 lines (90 loc) · 2.27 KB
/
Memg.java
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
import java.io.*;
import java.net.*;
import java.util.*;
public class Memg {
public static final Map<String, String> cache = new HashMap<String, String>();
public static void main(String[] args) {
ServerSocket sock = null;
try {
sock = new ServerSocket(11211);
} catch (IOException ex) {
ex.printStackTrace();
}
if (sock != null) {
if (find("--single", args)) {
try {
final Socket conn = sock.accept();
handleConnection(conn);
} catch (IOException ex) {
ex.printStackTrace();
}
} else {
while (true) {
try {
final Socket conn = sock.accept();
Thread t = new Thread() {
@Override
public void run() {
try {
handleConnection(conn);
} catch (IOException ex) {
ex.printStackTrace();
}
}
};
t.start();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
}
private static boolean find(String key, String[] arr) {
for (String s : arr) {
if (s.equals(key)) {
return true;
}
}
return false;
}
private static void handleConnection(Socket conn) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
PrintWriter out = new PrintWriter(conn.getOutputStream(), false);
while(true) {
String line = in.readLine();
if(line.equals(""))
break;
String[] parts = line.split(" ");
String cmd = parts[0];
if(cmd.equals("get")) {
String key = parts[1];
String val;
if(cache.containsKey(key)) {
val = cache.get(key);
out.printf("VALUE %s 0 %d\r\n", key, val.length());
out.printf("%s\r\n",val);
}
out.printf("END\r\n");
} else if(cmd.equals("set")) {
String key = parts[1];
int length = Integer.parseInt(parts[4]);
char[] buf = new char[length + 2]; //This is not 100% correct for handling unicode bytes, but it's fine here for the benchmark test
int index = 0;
while (index < buf.length) {
int len = in.read(buf, index, buf.length - index);
if (len == -1)
break;
index += len;
}
String val = new String(buf, 0, length);
cache.put(key, val);
out.printf("STORED\r\n");
} else {
System.out.println("Unknown cmd: " + cmd);
break;
}
out.flush();
}
}
}