forked from lee2018jian/airbnb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTCPServerThrottle
85 lines (68 loc) · 2.13 KB
/
TCPServerThrottle
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
import java.io.*;
import java.net.*;
// this is server side, not needed for client
// this is some made up code, just ignore this
public class TCPServerThrottle implements Runnable{
private ServerSocket serverSocket;
private double accelerationConstant = 0.0;
private long last = System.currentTimeMillis();
private double curSpeed = 0.0;
private double throttle = 0.0;
public TCPServerThrottle(int port) throws IOException {
serverSocket = new ServerSocket(port);
}
// naive update, does not consider other stuff
private void updateSpeed(long time) {
if(accelerationConstant < 0) {
time /= 1000;
while(time > 0 && curSpeed >= 0) {
curSpeed += accelerationConstant;
time--;
}
} else {
time /= 1000;
while(time > 0) {
curSpeed += accelerationConstant;
time--;
}
}
}
@Override
public void run() {
try {
Socket server = serverSocket.accept();
while(true) {
DataInputStream in = new DataInputStream(server.getInputStream());
DataOutputStream out = new DataOutputStream(server.getOutputStream());
long diffTime = System.currentTimeMillis() - last;
last = System.currentTimeMillis();
updateSpeed(diffTime);
String str = in.readUTF();
String[] res = str.split(" ");
if(res[0].equals("STATUS")) {
System.out.println("GOT STATUS Inquiry");
System.out.println();
out.writeUTF(throttle + " " + curSpeed);
} else {
double newThrottle = Double.parseDouble(res[1]);
System.out.println("Incoming throttle: " + newThrottle + ", old throttle:" + throttle);
if(newThrottle < throttle) {
accelerationConstant -= 0.5 * (throttle - newThrottle);
} else {
accelerationConstant += 0.5 * (newThrottle - throttle);
}
throttle = newThrottle;
System.out.println("accelerationConstant: " + accelerationConstant);
System.out.println();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
TCPServerThrottle c = new TCPServerThrottle(6603);
c.run();
}
}