Java Reference
In-Depth Information
execution begins when run() is called on an instance. The code in run() is almost identical to
the connection handling code in TCPEchoServer.java , except that a logging capability (described
shortly) has been added. The class implements the Runnable interface, so we can create a thread
that independently executes run() , or we can invoke run() directly.
EchoProtocol.java
0 import java.net.*; // for Socket
1 import java.io.*; // for IOException and Input/OutputStream
2 import java.util.*; // for ArrayList
3
4 class EchoProtocol implements Runnable {
5
static public final int BUFSIZE = 32;
// Size (in bytes) of I/O buffer
6
7
private Socket clntSock; // Connection socket
8
private Logger logger;
// Logging facility
9
10
public EchoProtocol(Socket clntSock, Logger logger) {
11
this.clntSock = clntSock;
12
this.logger = logger;
13
}
14
15
public void run() {
16
ArrayList entry = new ArrayList();
17
entry.add("Client address and port="+
18
clntSock.getInetAddress().getHostAddress() + ":" +
19
clntSock.getPort());
20
entry.add("Thread="+Thread.currentThread().getName());
21
22
try {
23
// Get the input and output I/O streams from socket
24
InputStream in = clntSock.getInputStream();
25
OutputStream out = clntSock.getOutputStream();
26
27
int recvMsgSize;
// Size of received message
28
int totalBytesEchoed = 0;
// Bytes received from client
29
byte[] echoBuffer = new byte[BUFSIZE]; // Receive Buffer
30
// Receive until client closes connection, indicated by −1
31
while ((recvMsgSize = in.read(echoBuffer)) != −1) {
32
out.write(echoBuffer, 0, recvMsgSize);
33
totalBytesEchoed += recvMsgSize;
34
}
35
36
entry.add("Client finished; echoed " + totalBytesEchoed + " bytes.");
37
} catch (IOException e) {
38
entry.add("Exception="+ e.getMessage());
39
}
 
Search WWH ::




Custom Search