java网络传输数据_使用Java来实现网络传输数据压缩的实例

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() );

}

// 剩下的是你自己的程序实现

}

现在你的通信数据得到了压缩.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值