Java Reference
In-Depth Information
Example 5•10: ProxyServer.java (continued)
// this program two variables would not work if declared final.
final Thread[] threads = new Thread[2];
// Define and create a thread to copy bytes from client to server
Thread c2s = new Thread() {
public void run() {
// Copy bytes 'till EOF from client
byte[] buffer = new byte[2048];
int bytes_read;
try {
while((bytes_read=from_client.read(buffer))!=-1) {
to_server.write(buffer, 0, bytes_read);
to_server.flush();
}
}
catch (IOException e) {}
finally {
// When the thread is done
try {
server.close(); // close the server socket
to_client.close(); // and the client streams
from_client.close();
}
catch (IOException e) {}
}
}
};
// Define and create a thread to copy bytes from server to client.
// This thread works just like the one above.
Thread s2c = new Thread() {
public void run() {
byte[] buffer = new byte[2048];
int bytes_read;
try {
while((bytes_read=from_server.read(buffer))!=-1) {
to_client.write(buffer, 0, bytes_read);
to_client.flush();
}
}
catch (IOException e) {}
finally {
try {
server.close(); // close down
to_client.close();
from_client.close();
} catch (IOException e) {}
}
}
};
// Store the threads into the final threads[] array, so that the
// anonymous classes can refer to each other.
threads[0] = c2s; threads[1] = s2c;
// start the threads
c2s.start(); s2c.start();
Search WWH ::




Custom Search