MINA传输文件

mina传输对象已经不是什么难事,一般啃半天代码就能搞定,但是传输文件似乎不是很容易,之前在论坛上求助过但是没有解决,还是靠自己啃代码解决了文件的上传和下载,以下只是随便测试写的代码供学习用(只是有很多朋友发邮件求代码思路这里我也就公布了,之前一直没有办法上网实在不好意思之前发邮件到qyhdt@sina.com邮箱求解的朋友们,我在这里给你们答案了实在不好意思),希望与大家一起探讨mina更多的强大功能。对于mina我也是个初学者。
首先我们创建一个上传下载公共文件流线程类






[java] view plaincopyprint?
01.package com.rose.common.frame.mina;
02.
03.import java.io.BufferedInputStream;
04.import java.io.BufferedOutputStream;
05.import java.io.IOException;
06.import java.io.InputStream;
07.import java.io.OutputStream;
08.
09./**
10. * 用于mina 服务器上传下载
11. * 流处理线程公共类
12. * @author qiuy
13. *
14. */
15.public class IoStreamThreadWork extends Thread{
16. public static final int BUFFER_SIZE = 1024*2;
17.
18. private BufferedInputStream bis;
19. private BufferedOutputStream bos;
20.
21.
22. public BufferedInputStream getBis() {
23. return bis;
24. }
25.
26. public void setBis(BufferedInputStream bis) {
27. this.bis = bis;
28. }
29.
30. public BufferedOutputStream getBos() {
31. return bos;
32. }
33.
34. public void setBos(BufferedOutputStream bos) {
35. this.bos = bos;
36. }
37.
38. public IoStreamThreadWork(InputStream in, OutputStream os){
39. bis = new BufferedInputStream(in);
40. bos = new BufferedOutputStream(os);
41. }
42. public synchronized void run() {
43. byte[] bufferByte = new byte[BUFFER_SIZE];
44. int tempData = 0;
45. try {
46. while((tempData = bis.read(bufferByte)) != -1 ){
47. bos.write(bufferByte, 0, tempData);
48. }
49. try {
50. bos.flush();
51. } catch (IOException e) {
52. e.printStackTrace();
53. }
54. } catch (IOException e) {
55. e.printStackTrace();
56. }finally{
57. try {
58. bos.close();
59. bis.close();
60. } catch (IOException e) {
61. e.printStackTrace();
62. }
63. }
64. }
65.}


写一个服务器端



[java] view plaincopyprint?
01.package com.rose.common.frame.mina;
02.
03.import java.io.File;
04.import java.io.FileNotFoundException;
05.import java.io.FileOutputStream;
06.import java.io.IOException;
07.import java.io.InputStream;
08.import java.io.OutputStream;
09.import java.net.InetSocketAddress;
10.import java.util.concurrent.ArrayBlockingQueue;
11.import java.util.concurrent.ThreadPoolExecutor;
12.import java.util.concurrent.TimeUnit;
13.
14.import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
15.import org.apache.mina.core.session.IoSession;
16.import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
17.import org.apache.mina.filter.logging.LoggingFilter;
18.import org.apache.mina.handler.stream.StreamIoHandler;
19.import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
20.
21./**
22. * @author qiuy
23. * 文件传输服务器
24. */
25.public class MinaFileServer extends StreamIoHandler{
26. public static final int PORT = 8888;
27. @Override
28. public void sessionOpened(IoSession session) {
29. System.out.println("客户端连接了:"+session.getRemoteAddress());
30. super.sessionOpened(session);
31. }
32.
33. protected void processStreamIo(IoSession session, InputStream in,OutputStream out) {
34. //设定一个线程池
35. //参数说明:最少数量3,最大数量6 空闲时间 3秒
36. ThreadPoolExecutor threadPool = new ThreadPoolExecutor(3, 6, 3,TimeUnit.SECONDS,
37. //缓冲队列为3
38. new ArrayBlockingQueue<Runnable>(3),
39. //抛弃旧的任务
40. new ThreadPoolExecutor.DiscardOldestPolicy());
41. FileOutputStream fos = null;
42. File receiveFile = new File("e:\\test.pdf");
43. try {
44. fos = new FileOutputStream(receiveFile);
45. } catch (FileNotFoundException e1) {
46. e1.printStackTrace();
47. }
48. //将线程放入线程池 当连接很多时候可以通过线程池处理
49. threadPool.execute(new IoStreamThreadWork(in,fos));
50. //直接启动线程 连接很少可以选用下面
51.// new IoStreamThreadWork(in,fos).start();
52. }
53.
54. public void createServerStream(){
55. //建立一个无阻塞服务端socket 用nio
56. NioSocketAcceptor acceptor = new NioSocketAcceptor();
57. //创建接收过滤器 也就是你要传送对象的类型
58. DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
59. //===========过滤器创建好了就开始设定============
60.
61. //设定 对象传输工厂
62. ObjectSerializationCodecFactory factory = new ObjectSerializationCodecFactory();
63. //设定传输最大值
64. factory.setDecoderMaxObjectSize(Integer.MAX_VALUE);// 设定后服务器可以接收大数据
65. factory.setEncoderMaxObjectSize(Integer.MAX_VALUE);
66. chain.addLast("logging", new LoggingFilter());//这个用于打印日志 可以不写
67. //设定服务端消息处理器
68. acceptor.setHandler(new MinaFileServer());
69. InetSocketAddress inetSocketAddress = null;
70. try {
71. inetSocketAddress = new InetSocketAddress(8888);
72. acceptor.bind(inetSocketAddress);
73. } catch (IOException e) {
74. // TODO Auto-generated catch block
75. e.printStackTrace();
76. }
77. System.out.println("文件服务器已经开启:"+8888);
78. }
79. public static void main(String[] args) {
80. MinaFileServer server = new MinaFileServer();
81. server.createServerStream();
82. }
83.}







[java] view plaincopyprint?
01.package com.rose.common.frame.mina;
02.
03.import java.io.File;
04.import java.io.FileInputStream;
05.import java.io.FileNotFoundException;
06.import java.io.InputStream;
07.import java.io.OutputStream;
08.import java.net.InetSocketAddress;
09.
10.import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
11.import org.apache.mina.core.future.ConnectFuture;
12.import org.apache.mina.core.session.IoSession;
13.import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
14.import org.apache.mina.filter.logging.LoggingFilter;
15.import org.apache.mina.handler.stream.StreamIoHandler;
16.import org.apache.mina.transport.socket.nio.NioSocketConnector;
17.
18.
19./**
20. * @author qiuy
21. * 文件传输客户端
22. */
23.public class MinaFileClient extends StreamIoHandler{
24. IoSession session;
25. public void setSession(IoSession session) {
26. this.session = session;
27. }
28. public IoSession getSession() {
29. return session;
30. }
31. @Override
32. protected void processStreamIo(IoSession session, InputStream in,
33. OutputStream out) {
34. //客户端发送文件
35. File sendFile = new File("F:\\ttt.pdf");
36. FileInputStream fis = null;
37. try {
38. fis = new FileInputStream(sendFile);
39.
40. } catch (FileNotFoundException e) {
41. e.printStackTrace();
42. }
43. //放入线程让其执行
44. //客户端一般都用一个线程实现即可 不用线程池
45. new IoStreamThreadWork(fis,out).start();
46. return;
47. }
48.
49. public void createClienStream(){
50. int port = 8888;
51. String local = "127.0.0.1";
52.
53. NioSocketConnector connector = new NioSocketConnector();
54. DefaultIoFilterChainBuilder chain = connector.getFilterChain();
55. ObjectSerializationCodecFactory factory = new ObjectSerializationCodecFactory();
56. factory.setDecoderMaxObjectSize(Integer.MAX_VALUE);
57. factory.setEncoderMaxObjectSize(Integer.MAX_VALUE);
58. chain.addLast("logging", new LoggingFilter());//用于打印日志可以不写
59. connector.setHandler(new MinaFileClient());
60. ConnectFuture connectFuture = connector.connect(new InetSocketAddress(local,port));
61. connectFuture.awaitUninterruptibly();//写上这句为了得到下面的session 意思是等待连接创建完成 让创建连接由异步变同步
62. //后来表明我开始的想法不行 动态依旧不能做到
63.// @SuppressWarnings("unused")
64.// IoSession session = connectFuture.getSession();
65.// setSession(session);
66. }
67. public static void main(String[] args) {
68. MinaFileClient client = new MinaFileClient();
69. client.createClienStream();
70. }
71.}



再写一个客户端
ok以上就可以实现客户端上传文件到服务器端 要是读者朋友想看看效果
代码拷贝后 在自己的f盘下放一个ttt.pdf然后运行服务器端,再运行客户端这样在你的e盘下会多出一个叫test.pdf文件。如果要用到具体工程中请自行封装一下代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值