Java Reference
In-Depth Information
39
int recvMsgSize;
// Size of received message
40
int totalBytesEchoed = 0;
// Bytes received from client
41
byte[] echoBuffer = new byte[BUFSIZE]; // Receive buffer
42
long endTime = System.currentTimeMillis() + timelimit;
43
int timeBoundMillis = timelimit;
44
45
clntSock.setSoTimeout(timeBoundMillis);
46
47
// Receive until client closes connection, indicated by −1
48
while ((timeBoundMillis > 0) &&
// catch zero values
49
((recvMsgSize = in.read(echoBuffer)) != −1)) {
50
out.write(echoBuffer, 0, recvMsgSize);
51
totalBytesEchoed += recvMsgSize;
52
timeBoundMillis = (int) (endTime − System.currentTimeMillis()) ;
53
clntSock.setSoTimeout(timeBoundMillis);
54
}
55
56
entry.add("Client finished; echoed " + totalBytesEchoed + " bytes.");
57
} catch (InterruptedIOException dummy) {
58
entry.add("Read timed out");
59
} catch (IOException e) {
60
entry.add("Exception="+ e.getMessage());
61
}
62
63
try { // Close socket
64
clntSock.close();
65
} catch (IOException e) {
66
entry.add("Exception="+ e.getMessage());
67
}
68
69
logger.writeEntry(entry);
70
}
71 }
TimelimitEchoProtocolFactory.java
TimelimitEchoProtocolFactory.java contains both the factory and protocol instance
classes. The factory is exactly like EchoProtocolFactory , with the exception that it instantiates
TimelimitEchoProtocol instead of EchoProtocol . The TimelimitEchoProtocol class is similar to
the EchoProtocol class, except that it attempts to bound the total time an echo connection can
exist. The default time is 10 seconds; the total number of milliseconds per connection can be
set using the “Timelimit” property.
Another approach to limiting client service time involves starting two threads per client:
one that executes the protocol and another that acts as a “watchdog,” sleeping until
timelimit
milliseconds pass or the other (protocol) thread finishes and interrupts it, whichever comes
Search WWH ::




Custom Search