-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStudentSocketImpl_Old.java
524 lines (457 loc) · 17.5 KB
/
StudentSocketImpl_Old.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
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
import java.net.*;
import java.io.*;
import java.util.*;
class StudentSocketImpl extends BaseSocketImpl {
private Demultiplexer D;
private Timer tcpTimer;
private int state;
private int seqNum;
private int ackNum;
private PipedOutputStream appOS;
private PipedInputStream appIS;
private PipedInputStream pipeAppToSocket;
private PipedOutputStream pipeSocketToApp;
private SocketReader reader;
private SocketWriter writer;
private boolean terminating = false;
private InfiniteBuffer sendBuffer;
private InfiniteBuffer recvBuffer;
private Hashtable<Integer, TCPTimerTask> timerList; //holds the timers for sent packets
private Hashtable<Integer, TCPPacket> packetList; //holds the packets associated with each timer
//(for timer identification)
private boolean wantsToClose = false;
private boolean finSent = false;
private static final int CLOSED = 0;
private static final int SYN_SENT = 1;
private static final int LISTEN = 2;
private static final int SYN_RCVD = 3;
private static final int ESTABLISHED = 4;
private static final int FIN_WAIT_1 = 5;
private static final int FIN_WAIT_2 = 6;
private static final int CLOSING = 7;
private static final int CLOSE_WAIT = 8;
private static final int LAST_ACK = 9;
private static final int TIME_WAIT = 10;
StudentSocketImpl(Demultiplexer D) { // default constructor
this.D = D;
state = CLOSED;
seqNum = -1;
ackNum = -1;
timerList = new Hashtable<Integer, TCPTimerTask>();
packetList = new Hashtable<Integer, TCPPacket>();
this.D = D;
try {
pipeAppToSocket = new PipedInputStream();
pipeSocketToApp = new PipedOutputStream();
appIS = new PipedInputStream(pipeSocketToApp);
appOS = new PipedOutputStream(pipeAppToSocket);
}
catch(IOException e){
System.err.println("unable to create piped sockets");
System.exit(1);
}
initBuffers();
reader = new SocketReader(pipeAppToSocket, this);
reader.start();
writer = new SocketWriter(pipeSocketToApp, this);
writer.start();
initBuffers();
}
private String stateString(int inState){
if (inState == 0){
return "CLOSED";
}
else if (inState == 1){
return "SYN_STATE";
}
else if (inState == 2){
return "LISTEN";
}
else if (inState == 3){
return "SYN_RCVD";
}
else if (inState == 4){
return "ESTABLISHED";
}
else if (inState == 5){
return "FIN_WAIT_1";
}
else if (inState == 6){
return "FIN_WAIT_2";
}
else if (inState == 7){
return "CLOSING";
}
else if (inState == 8){
return "CLOSE_WAIT";
}
else if (inState == 9){
return "LAST_ACK";
}
else if (inState == 10){
return "TIME_WAIT";
}
else{
return "Invalid state number";
}
}
private synchronized void changeToState(int newState) {
System.out.println("!!! " + stateString(state) + "->" + stateString(newState));
state = newState;
if (newState == CLOSE_WAIT && wantsToClose && !finSent) {
try {
close();
}
catch(IOException ioe){}
}
else if (newState == TIME_WAIT) {
createTimerTask(30000, null);
}
}
/**
* initialize buffers and set up sequence numbers
*/
private void initBuffers() {
sendBuffer = new InfiniteBuffer(10000);
recvBuffer = new InfiniteBuffer(10000);
}
/**
* Called by the application-layer code to copy data out of the
* recvBuffer into the application's space.
* Must block until data is available, or until terminating is true
*
* @param buffer array of bytes to return to application
* @param length desired maximum number of bytes to copy
* @return number of bytes copied (by definition > 0)
*/
synchronized int getData(byte[] buffer, int length){
return 0;
}
/**
* accept data written by application into sendBuffer to send.
* Must block until ALL data is written.
*
* @param buffer array of bytes to copy into app
* @param length number of bytes to copy
*/
synchronized void dataFromApp(byte[] buffer, int length) {
System.out.println("send test");
sendBuffer.append(buffer, 0, length);
sendData(sendBuffer);
}
/**
* probably just call sendPacket a bunch
* @param buffer
* @param length
*/
synchronized void sendData(InfiniteBuffer buffer) {
byte [] printarray = new byte [buffer.getBufferSize()];
buffer.copyOut(printarray, 0, buffer.getBufferSize());
for (int i=0; i < printarray.length; i++){
System.out.println(printarray[i]);
}
}
private synchronized void sendPacket(TCPPacket inPacket, boolean resend){
if(inPacket.ackFlag == true && inPacket.synFlag == false){
inPacket.seqNum = -2;
}
if(resend == false){ //new timer, and requires the current state as a key
TCPWrapper.send(inPacket, address);
//only do timers for syns, syn-acks, and fins
if(inPacket.synFlag == true || inPacket.finFlag == true){
System.out.println("creating new TimerTask at state " + stateString(state));
timerList.put(new Integer(state),createTimerTask(1000, inPacket));
packetList.put(new Integer(state), inPacket);
}
}
else{ //the packet is for resending, and requires the original state as the key
Enumeration keyList = timerList.keys();
Integer currKey = new Integer(-1);
try{
for(int i = 0; i<10; i++){
currKey = (Integer)keyList.nextElement();
if(packetList.get(currKey) == inPacket){
System.out.println("Recreating TimerTask from state " + stateString(currKey));
TCPWrapper.send(inPacket, address);
timerList.put(currKey,createTimerTask(1000, inPacket));
break;
}
}
}
catch(NoSuchElementException nsee){
}
}
}
private synchronized void incrementCounters(TCPPacket p){
ackNum = p.seqNum + 1;
if(p.ackNum != -1)
seqNum = p.ackNum;
}
private synchronized void cancelPacketTimer(){
//must be called before changeToState is called!!!
int i;
if(state != CLOSING){
for (i=0; i<ackNum; i++){
if (timerList.containsKey(i)){
timerList.get(i).cancel();
timerList.remove(i);
}
if (packetList.containsKey(i)){
packetList.remove(i);
}
}
}
else{
//the only time the state changes before an ack is received... so it must
//look back to where the fin timer started
timerList.get(FIN_WAIT_1).cancel();
timerList.remove(FIN_WAIT_1);
packetList.remove(FIN_WAIT_1);
}
}
/**
* Connects this socket to the specified port number on the specified host.
*
* @param address the IP address of the remote host.
* @param port the port number.
* @exception IOException if an I/O error occurs when attempting a
* connection.
*/
public synchronized void connect(InetAddress address, int port) throws IOException{
//client state
localport = D.getNextAvailablePort();
this.address = address;
this.port = port;
D.registerConnection(address, localport, port, this);
seqNum = 100;
TCPPacket synPacket = new TCPPacket(localport, port, seqNum, ackNum, false, true, false, 1, null);
changeToState(SYN_SENT);
sendPacket(synPacket, false);
}
/**
* Called by Demultiplexer when a packet comes in for this connection
* @param p The packet that arrived
*/
public synchronized void receivePacket(TCPPacket p){
this.notifyAll();
System.out.println("Packet received from address " + p.sourceAddr + " with seqNum " + p.seqNum + " is being processed.");
System.out.print("The packet is ");
if(p.ackFlag == true && p.synFlag == true){
System.out.println("a syn-ack.");
if(state == SYN_SENT){
//client state
incrementCounters(p);
cancelPacketTimer();
TCPPacket ackPacket = new TCPPacket(localport, port, seqNum, ackNum, true, false, false, 1, null);
changeToState(ESTABLISHED);
sendPacket(ackPacket, false);
}
else if (state == ESTABLISHED){
//client state, strange message due to packet loss
TCPPacket ackPacket = new TCPPacket(localport, port, seqNum, ackNum, true, false, false, 1, null);
sendPacket(ackPacket, false);
}
else if (state == FIN_WAIT_1){
//client state, strange message due to packet loss
TCPPacket ackPacket = new TCPPacket(localport, port, seqNum, ackNum, true, false, false, 1, null);
sendPacket(ackPacket, false);
}
}
else if(p.ackFlag == true){
System.out.println("an ack.");
//for the love of God, do not incrementCounters(p) in here
if(state == SYN_RCVD){
//server state
cancelPacketTimer();
changeToState(ESTABLISHED);
}
else if(state == FIN_WAIT_1){
//client state
cancelPacketTimer();
changeToState(FIN_WAIT_2);
}
else if(state == LAST_ACK){
//server state
cancelPacketTimer();
changeToState(TIME_WAIT);
}
else if(state == CLOSING){
//client or server state
cancelPacketTimer();
changeToState(TIME_WAIT);
}
}
else if(p.synFlag == true){
System.out.println("a syn.");
if(state == LISTEN){
//server state
try{
D.unregisterListeningSocket(localport, this); //***********tricky*************
D.registerConnection(p.sourceAddr, p.destPort, p.sourcePort, this); //***********tricky*************
}
catch(IOException e){
System.out.println("Error occured while attempting to establish connection");
}
this.address = p.sourceAddr;
this.port = p.sourcePort;
incrementCounters(p);
TCPPacket synackPacket = new TCPPacket(localport, port, seqNum, ackNum, true, true, false, 1, null);
changeToState(SYN_RCVD);
sendPacket(synackPacket, false);
}
}
else if(p.finFlag == true){
System.out.println("a fin.");
if(state == ESTABLISHED){
//server state
incrementCounters(p);
TCPPacket ackPacket = new TCPPacket(localport, port, seqNum, ackNum, true, false, false, 1, null);
changeToState(CLOSE_WAIT);
sendPacket(ackPacket, false);
}
else if(state == FIN_WAIT_1){
//client state or server state
incrementCounters(p);
TCPPacket ackPacket = new TCPPacket(localport, port, seqNum, ackNum, true, false, false, 1, null);
changeToState(CLOSING);
sendPacket(ackPacket, false);
}
else if(state == FIN_WAIT_2){
//client state
incrementCounters(p);
TCPPacket ackPacket = new TCPPacket(localport, port, seqNum, ackNum, true, false, false, 1, null);
changeToState(TIME_WAIT);
sendPacket(ackPacket, false);
}
else if(state == LAST_ACK){
//server state, strange message due to packet loss
TCPPacket ackPacket = new TCPPacket(localport, port, seqNum, ackNum, true, false, false, 1, null);
sendPacket(ackPacket, false);
}
else if(state == CLOSING){
//client or server state, strange message due to packet loss
TCPPacket ackPacket = new TCPPacket(localport, port, seqNum, ackNum, true, false, false, 1, null);
sendPacket(ackPacket, false);
}
else if(state == TIME_WAIT){
//client or server state, strange message due to packet loss
TCPPacket ackPacket = new TCPPacket(localport, port, seqNum, ackNum, true, false, false, 1, null);
sendPacket(ackPacket, false);
}
}
else{
System.out.println("a chunk of data.");
}
}
/**
* Waits for an incoming connection to arrive to connect this socket to
* Ultimately this is called by the application calling
* ServerSocket.accept(), but this method belongs to the Socket object
* that will be returned, not the listening ServerSocket.
* Note that localport is already set prior to this being called.
*/
public synchronized void acceptConnection() throws IOException {
//server state
changeToState(LISTEN);
D.registerListeningSocket (localport, this);
seqNum = 1000;
try{
this.wait();
}
catch(InterruptedException e){
System.err.println("Error occured when trying to wait.");
}
}
/**
* Returns an input stream for this socket. Note that this method cannot
* create a NEW InputStream, but must return a reference to an
* existing InputStream (that you create elsewhere) because it may be
* called more than once.
*
* @return a stream for reading from this socket.
* @exception IOException if an I/O error occurs when creating the
* input stream.
*/
public InputStream getInputStream() throws IOException {return appIS;}
/**
* Returns an output stream for this socket. Note that this method cannot
* create a NEW InputStream, but must return a reference to an
* existing InputStream (that you create elsewhere) because it may be
* called more than once.
*
* @return an output stream for writing to this socket.
* @exception IOException if an I/O error occurs when creating the
* output stream.
*/
public OutputStream getOutputStream() throws IOException {return appOS;}
/**
* Closes this socket.
*
* @exception IOException if an I/O error occurs when closing this socket.
*/
public synchronized void close() throws IOException {
if (address == null)
return;
terminating = true;
while(!reader.tryClose()){
notifyAll();
try {
wait(1000);
} catch(InterruptedException e){}
}
writer.close();
notifyAll();
if(state == ESTABLISHED){
//client state
TCPPacket finPacket = new TCPPacket(localport, port, seqNum, ackNum, false, false, true, 1, null);
changeToState(FIN_WAIT_1);
sendPacket(finPacket, false);
finSent = true;
}
else if(state == CLOSE_WAIT){
//server state
TCPPacket finPacket = new TCPPacket(localport, port, seqNum, ackNum, false, false, true, 1, null);
changeToState(LAST_ACK);
sendPacket(finPacket, false);
finSent = true;
}
else{
System.out.println("Attempted to close while not established (ESTABLISHED) or waiting to close (CLOSE_WAIT)");
//timer task here... try the closing process again
wantsToClose = true;
}
//returns immediately to the application
}
/**
* create TCPTimerTask instance, handling tcpTimer creation
* @param delay time in milliseconds before call
* @param ref generic reference to be returned to handleTimer
*/
private TCPTimerTask createTimerTask(long delay, Object ref){
if(tcpTimer == null)
tcpTimer = new Timer(false);
return new TCPTimerTask(tcpTimer, delay, this, ref);
}
/**
* handle timer expiration (called by TCPTimerTask)
* @param ref Generic reference that can be used by the timer to return
* information.
*/
public synchronized void handleTimer(Object ref){
if(ref == null){
// this must run only once the last timer (30 second timer) has expired
tcpTimer.cancel();
tcpTimer = null;
try{
D.unregisterConnection(address, localport, port, this);
}
catch(IOException e){
System.out.println("Error occured while attempting to close connection");
}
}
else{ //its a packet that needs to be resent
System.out.println("XXX Resending Packet");
sendPacket((TCPPacket)ref, true);
}
}
}