服务系统优化到一定程度后,提高性能的瓶颈可能就在于数据的网络传输上。因为在一天的任何时间内,都有可能在客户端和服务器端之间传送成千上万的大数据,这需要占用很大的带宽,严重影响客户端的体验。
一种可能的解决办法,我们希望能够在把数据返回给客户端前,先压缩这些数据。如果传输的是文件,图片之类的,网络已经有了很多介绍。但是我们所需要的----对网络传输数据进行压缩。
当使用ZipInputStream 和 ZipOutputStream压缩处理时,并没有强制你只能压缩文件。唯一要注意的是你必须把数据转换为字节数组的形式。
以下是创建一个RMI形式的套接字的简要步骤:
1、选择或者创建一个新的套接字.
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() );
}
// 剩下的是你自己的程序实现
}
至此,你的通信数据已经得到了压缩。