Mina发送文件的客户端实现

实现步骤:

   1.建立一个无阻塞服务端socket 用nio
   2.创建接收过滤器 也就是你要传送对象的类型

   3.设定 对象传输工厂
   4.设定传输最大值
   5.设定服务端消息处理器, 将线程放入线程池 当连接很多时候可以通过线程池处理       

       NioSocketConnector connector = new NioSocketConnector();  
        DefaultIoFilterChainBuilder chain = connector.getFilterChain();  
        ObjectSerializationCodecFactory factory = new ObjectSerializationCodecFactory();  
        factory.setDecoderMaxObjectSize(Integer.MAX_VALUE);  
        factory.setEncoderMaxObjectSize(Integer.MAX_VALUE);  
        chain.addLast("logging", new LoggingFilter());//用于打印日志可以不写  
        connector.setHandler(new MinaFileClient(filePath));  
        ConnectFuture connectFuture = connector.connect(new InetSocketAddress(local,port));  
        connectFuture.awaitUninterruptibly();//写上这句为了得到下面的session 意思是等待连接创建完成 让创建连接由异步变同步  

package cn.org.handler;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.handler.stream.StreamIoHandler;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import cn.org.util.IoStreamThreadWork;  

  
  
/** 
 * @author changyaobin
 * 文件传输客户端  
 */  
public class MinaFileClient extends StreamIoHandler{  
    IoSession session;  
    private String filePath;
   
	public void setSession(IoSession session) {  
        this.session = session;  
    }  
    public IoSession getSession() {  
        return session;    
    }  
    @Override  
    protected void processStreamIo(IoSession session, InputStream in,  
            OutputStream out) {  
        //客户端发送文件  
            File sendFile = new File(this.filePath);  
            FileInputStream fis = null;  
            try {  
                fis = new FileInputStream(sendFile);  
                  
            } catch (FileNotFoundException e) {  
                e.printStackTrace();  
            }  
            //放入线程让其执行  
             //客户端一般都用一个线程实现即可 不用线程池  
            new IoStreamThreadWork(fis,out).start();  
            return;  
    }  
      
    public void createClienStream(){  
        int port = 8888;  
        String local = "127.0.0.1";  
          
        NioSocketConnector connector = new NioSocketConnector();  
        DefaultIoFilterChainBuilder chain = connector.getFilterChain();  
        ObjectSerializationCodecFactory factory = new ObjectSerializationCodecFactory();  
        factory.setDecoderMaxObjectSize(Integer.MAX_VALUE);  
        factory.setEncoderMaxObjectSize(Integer.MAX_VALUE);  
        chain.addLast("logging", new LoggingFilter());//用于打印日志可以不写  
        connector.setHandler(new MinaFileClient(filePath));  
        ConnectFuture connectFuture = connector.connect(new InetSocketAddress(local,port));  
        connectFuture.awaitUninterruptibly();//写上这句为了得到下面的session 意思是等待连接创建完成 让创建连接由异步变同步  
    }  
	public MinaFileClient(String filePath) {
		super();
		this.filePath = filePath;
	}  
	public MinaFileClient() {
		super();
	} 
}  

接下来,实现IoStreamThreadWork多线程

package cn.org.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

  
/** 
 * 用于mina 服务器上传下载 
 * 流处理线程公共类 
 * @author changyaobin
 * 
 */  
public class IoStreamThreadWork extends Thread{  
    public static final int BUFFER_SIZE = 1024*1000;  
    private static final int fileHeadCheckSiteStart = 30;//此处代表字节
    private static final int fileHeadCheckSiteLength = 2;//此处代表字节
	private static String path = "resources";
    private BufferedInputStream bis;  
    private BufferedOutputStream bos;  
      
      
    public BufferedInputStream getBis() {  
        return bis;  
    }  
  
    public void setBis(BufferedInputStream bis) {  
        this.bis = bis;  
    }  
  
    public BufferedOutputStream getBos() {  
        return bos;  
    }  
  
    public void setBos(BufferedOutputStream bos) {  
        this.bos = bos;  
    }  
  
    public IoStreamThreadWork(InputStream in, OutputStream os){  
        bis = new BufferedInputStream(in);  
        bos = new BufferedOutputStream(os);  
    }  
    public synchronized void run() {  
        byte[] bufferByte = new byte[BUFFER_SIZE];  
        int tempData = 0;  
        StringBuffer hexs = new StringBuffer(); 
        DecodeFile decodeFile = null;
        try {  
        	while((tempData = bis.read(bufferByte)) != -1 ){  
                bos.write(bufferByte, 0, tempData);  
                //转储为16进制字符串数组
                //注:字节转换为16进制字符串,1个字节变两个16进制字符串
                String[] hexTemps = Bytes2AllType.bytes2Hexs(bufferByte, 0, tempData);
                for (String str : hexTemps) {
					hexs.append(str);
				}
            }  

            try {  
                bos.flush();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        } catch (InstantiationException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IllegalAccessException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}finally{  
            try {  
                bos.close();  
                bis.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
    }  
}  

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值