1:選擇或者創建一個新的套接字。(可以參看SUN´S的"創建一個典型的套接字")。
2:創建一個服務器端的套接字
3:創建一個RMIClientSocketFactory
4:創建一個RMIServerSocketFactory
5:創建一個繼承了UnicastRemoteObjec的遠程對象,從而使用新的factories
根據這一大致的想法,我們來看每一步如何具體的實現。
步驟1: 創建ZipSocket
由於要進行Zip壓縮,我們重新創建這樣的套接字
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import java.net.Socket;
public class ZipSocket extends Socket {
private InputStream in;
private OutputStream out;
public ZipSocket() { super(); }
public ZipSocket(String host, int port) throws IOException {
super(host, port);
}
public InputStream getInputStream() throws IOException {
if (in == null) {
in = new ZipInputStream(super.getInputStream());
}
return in;
}
public OutputStream getOutputStream() throws IOException {
if (out == null) {
out = new ZipOutputStream(super.getOutputStream());
}
return out;
}
public synchronized void close() throws IOException {
OutputStream o = getOutputStream();
o.flush();
super.close();
}
}
步驟2: 創建ZipServerSocket
import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException
public class ZipServerSocket extends ServerSocket{
public ZipServerSocket(int port) throws IOException {
super(port);
}
public Socket accept() throws IOException {
Socket socket = new ZipSocket();
implAccept(socket);
return socket;
}
}
步驟3:創建ZipClientSocketFactory
客戶端的factory的創建必須遵循以下的形式:
import java.io.IOException;
import java.io.Serializable;
import java.net.Socket;
import java.rmi.server.RMIClientSocketFactory;
public class ZipClientSocketFactory
implements RMIClientSocketFactory, Serializable {
public Socket createSocket(String host, int port) throws IOException {
ZipSocket socket = new ZipSocket(host, port);
return socket;
}
}
步驟4:創建ZipServerSocketFactory
import java.io.IOException;
import java.io.Serializable;
import java.net.ServerSocket;
import java.rmi.server.RMIServerSocketFactory;
public class ZipServerSocketFactory
implements RMIServerSocketFactory, Serializable {
public ServerSocket createServerSocket(int port) throws IOException {
ZipServerSocket server = new ZipServerSocket(port);
return server;
}
}
步驟5: 創建一個繼承了UnicastRemoteObjec的遠程對象,從而使用新的factories.
public class YourRMIObject extends UnicastRemoteObject {
public YourRemoteObject( int port ) {
super( port, new ZipClientSocketFactory(), new ZipServerSocketFactory() );
}
// 剩下的是你自己的程序實現
}
現在你的通信數據得到了壓縮.