-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTCPSocketImpl.java
More file actions
306 lines (284 loc) · 11.2 KB
/
TCPSocketImpl.java
File metadata and controls
306 lines (284 loc) · 11.2 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
import java.io.*;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Timer;
import java.util.TimerTask;
public class TCPSocketImpl extends TCPSocket {
private EnhancedDatagramSocket UDPSocket;
private InetAddress serverIp;
private int serverPort;
private int SSThreshold;
private static final int DefaultSSThreshold = 100;
private long seq = 100;
private long expectedSeq;
private final int timeout = 2000;
private int duplicateAcks;
private float windowSize;
private int lastSentIndex;
private ArrayList<TCPPacket> window = new ArrayList<>();
private Timer timer;
public enum State {
NONE, // client
SYN_SENT, // client
SYN_RECEIVED, // server
ESTABLISHED, // client
SLOW_START, // server
CONGESTION_AVOIDANCE, // server
FAST_RECOVERY // server
}
private State state;
private TCPSocketImpl(String ip, int port, State state) throws Exception {
super(ip, port);
this.UDPSocket = new EnhancedDatagramSocket(0);
this.serverIp = InetAddress.getByName(ip);
this.serverPort = port;
this.state = state;
this.lastSentIndex = -1;
this.SSThreshold = DefaultSSThreshold;
this.windowSize = this.getMSS();
this.duplicateAcks = 0;
this.onWindowChange();
}
public TCPSocketImpl(String ip, int port) throws Exception { // for client
this(ip, port, State.NONE);
TCPPacket packet = new TCPPacket(seq++, (long) (0), false, true, null);
UDPSocket.send(new DatagramPacket(packet.toUDPData(), packet.getBytesNumber(),
this.serverIp, this.serverPort));
this.state = State.SYN_SENT;
DatagramPacket UDPPacket = null;
TCPPacket req = null;
while (req == null || !(req.getSYN() && req.getACK()
&& req.getAcknowledgementNumber() == this.seq)) {
if (req != null)
System.err.println("Invalid TCP Package");
byte[] data = new byte[this.UDPSocket.getPayloadLimitInBytes()];
UDPPacket = new DatagramPacket(data, data.length);
UDPSocket.receive(UDPPacket);
req = new TCPPacket(data);
}
this.serverPort = UDPPacket.getPort();
this.expectedSeq = req.getSequenceNumber() + 1;
this.state = State.SLOW_START;
TCPPacket res = new TCPPacket(seq++, req.getSequenceNumber() + 1,
true, false, null);
this.UDPSocket.send(new DatagramPacket(res.toUDPData(), res.getBytesNumber(),
this.serverIp, this.serverPort));
}
public TCPSocketImpl(String ip, int port, TCPPacket handshakingReq) throws Exception { // for server
this(ip, port, State.SYN_RECEIVED);
TCPPacket res = new TCPPacket(seq++, handshakingReq.getSequenceNumber() + 1,
true, true, null);
this.UDPSocket.send(new DatagramPacket(res.toUDPData(), res.getBytesNumber(),
this.serverIp, this.serverPort));
TCPPacket req = null;
while (req == null || !(!req.getSYN() && req.getACK()
&& req.getAcknowledgementNumber() == this.seq)) {
if (req != null)
System.err.println("Invalid TCP Package");
byte[] data = new byte[this.UDPSocket.getPayloadLimitInBytes()];
DatagramPacket UDPPacket = new DatagramPacket(data, data.length);
UDPSocket.receive(UDPPacket);
req = new TCPPacket(data);
}
this.expectedSeq = req.getSequenceNumber() + 1;
this.state = State.ESTABLISHED;
}
public int getMSS() {
return 1;
}
public void handleLoss(boolean didTimeout) throws Exception {
if(this.state == State.CONGESTION_AVOIDANCE){
if(didTimeout){
this.state = State.SLOW_START;
this.SSThreshold = (int) (this.windowSize / 2);
this.windowSize = 1;
this.onWindowChange();
this.lastSentIndex = -1;
}
else{
this.state = State.FAST_RECOVERY;
this.SSThreshold = (int) (this.windowSize / 2);
this.windowSize = this.SSThreshold + 3;
this.onWindowChange();
this.lastSentIndex = -1;
}
this.send();
}
else if(this.state == State.FAST_RECOVERY){
if(didTimeout){
this.state = State.SLOW_START;
this.SSThreshold = (int) (this.windowSize / 2);
this.windowSize = 1;
this.onWindowChange();
this.lastSentIndex = -1;
}
else{
this.state = State.FAST_RECOVERY;
this.windowSize = this.windowSize + 1;
this.onWindowChange();
this.lastSentIndex = -1;
}
this.send();
}
}
private void resetTimer() {
if (timer != null)
timer.cancel();
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
try {
handleLoss(true);
} catch (Exception e) {
e.printStackTrace();
}
}
}, timeout);
}
private void windowPop() {
resetTimer();
window.remove(0);
this.lastSentIndex--;
if (timer != null && this.window.size() == 0)
timer.cancel();
}
private void windowPush(TCPPacket packet) {
if (this.window.size() == 0)
resetTimer();
this.window.add(packet);
}
private void windowPush(Collection<? extends TCPPacket> packets) {
if (this.window.size() == 0)
resetTimer();
this.window.addAll(packets);
}
private void send() throws Exception {
for (int i = this.lastSentIndex + 1; i < windowSize && i < window.size(); i++) {
TCPPacket packet = window.get(i);
this.UDPSocket.send(new DatagramPacket(packet.toUDPData(), packet.getBytesNumber(),
this.serverIp, this.serverPort));
this.lastSentIndex = i;
}
}
private void ackReceive() throws Exception {
TCPPacket ack;
while (true) {
ack = null;
while (ack == null || !(ack.getACK())) {
byte[] ackData = new byte[this.UDPSocket.getPayloadLimitInBytes()];
UDPSocket.receive(new DatagramPacket(ackData, ackData.length));
ack = new TCPPacket(ackData);
}
int firstUnackedPacketIndex;
for (firstUnackedPacketIndex = 0; firstUnackedPacketIndex < window.size(); firstUnackedPacketIndex++)
if (ack.getAcknowledgementNumber()
< window.get(firstUnackedPacketIndex).getExpectedAcknowledgementNumber())
break;
if (firstUnackedPacketIndex == 0) {
duplicateAcks++;
if (duplicateAcks == 3) {
this.handleLoss(false);
}
continue;
}
this.duplicateAcks = 0;
for (int j = 0; j < firstUnackedPacketIndex; j++) {
this.windowPop();
switch (this.state) {
case CONGESTION_AVOIDANCE:
this.windowSize += this.getMSS() * this.getMSS() / this.windowSize;
break;
case SLOW_START:
this.windowSize += this.getMSS();
if (this.windowSize > this.SSThreshold) {
this.state = State.CONGESTION_AVOIDANCE;
}
break;
case FAST_RECOVERY:
this.windowSize += this.getMSS();
this.state = State.CONGESTION_AVOIDANCE;
break;
}
this.onWindowChange();
}
break;
}
}
private byte[] receive() throws Exception {
byte[] data = new byte[this.UDPSocket.getPayloadLimitInBytes()];
this.UDPSocket.receive(new DatagramPacket(data, data.length));
TCPPacket req = new TCPPacket(data);
byte[] ret = null;
if (req.getSequenceNumber() == this.expectedSeq) {
this.expectedSeq += req.getDataLength() + 1;
ret = req.getData();
} else {
System.err.println("Invalid TCP Package");
System.err.println("seq: " + req.getSequenceNumber() + " exp: " + this.expectedSeq);
}
TCPPacket res = new TCPPacket(seq++, this.expectedSeq, true, false, null);
this.UDPSocket.send(new DatagramPacket(res.toUDPData(), res.getBytesNumber(),
this.serverIp, this.serverPort));
return ret;
}
@Override
public void send(String pathToFile) throws Exception {
File file = new File(pathToFile);
BufferedInputStream buffer = new BufferedInputStream(new FileInputStream(file));
ArrayList<TCPPacket> packets = new ArrayList<TCPPacket>();
int readBytes = 0;
while (readBytes < file.length()) {
packets.clear();
for (int i = 0; windowSize > lastSentIndex + i + 1 && readBytes < file.length(); i++) {
byte[] data = new byte[this.UDPSocket.getPayloadLimitInBytes() - TCPPacket.dataOffsetByBytes];
int length = buffer.read(data, 0, data.length);
if (length == -1)
break;
readBytes += length;
TCPPacket packet = new TCPPacket(seq, Arrays.copyOfRange(data, 0, length));
packets.add(packet);
seq += packet.getDataLength() + 1;
}
this.windowPush(packets);
this.send();
ackReceive();
}
buffer.close();
TCPPacket finPacket = new TCPPacket(seq, null);
seq += finPacket.getDataLength() + 1;
this.windowPush(finPacket);
while (window.size() > 0) {
this.send();
ackReceive();
}
}
@Override
public void receive(String pathToFile) throws Exception {
BufferedOutputStream buffer = new BufferedOutputStream(new FileOutputStream(new File(pathToFile)));
while (true) {
byte[] data = this.receive();
if (data == null)
continue;
if (data.length == 0)
break;
buffer.write(data);
}
buffer.close();
}
@Override
public void close() throws Exception {
this.UDPSocket.close();
}
@Override
public long getSSThreshold() {
return SSThreshold;
}
@Override
public long getWindowSize() {
return (long) windowSize;
}
}