使用Java实现网络传输数据压缩的实例
时间:2009-12-07
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() );
}
// 剩下的是你自己的程序实现
}
现在你的通信数据得到了压缩. |