博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Mina传输图片
阅读量:6094 次
发布时间:2019-06-20

本文共 6133 字,大约阅读时间需要 20 分钟。

  hot3.png

Server:

package mina.example3;import java.net.InetSocketAddress;import org.apache.mina.filter.codec.ProtocolCodecFilter;import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;import org.apache.mina.filter.logging.LoggingFilter;import org.apache.mina.transport.socket.nio.NioSocketAcceptor;/** *  * @author dujinkai * */public class FileTransServer{	public static void main(String[] args)  throws Exception	{		ObjectSerializationCodecFactory objectSerializationCodecFactory = new ObjectSerializationCodecFactory();				objectSerializationCodecFactory.setDecoderMaxObjectSize(Integer.MAX_VALUE);		objectSerializationCodecFactory.setEncoderMaxObjectSize(Integer.MAX_VALUE);				NioSocketAcceptor accept=new NioSocketAcceptor(); 		accept.getFilterChain().addLast("codec",				new ProtocolCodecFilter(objectSerializationCodecFactory));				accept.getFilterChain().addLast("logging", new LoggingFilter()); 		accept.setHandler(new FileIOHandle());				accept.bind(new InetSocketAddress(8998));  	}}

Handler:

package mina.example3;import java.io.File;import java.io.FileOutputStream;import org.apache.mina.core.service.IoHandler;import org.apache.mina.core.session.IdleStatus;import org.apache.mina.core.session.IoSession;/** * 文件业务处理 * @author dujinkai * */public class FileIOHandle implements IoHandler{	public void exceptionCaught(IoSession arg0, Throwable arg1)			throws Exception {			}	public void messageReceived(IoSession arg0, Object arg1) throws Exception	{		System.out.println("Receive Message:" + arg1);		FileUploadRequest fileUploadRequest = null;		if (arg1 instanceof FileUploadRequest )		{			fileUploadRequest = (FileUploadRequest)arg1;			String  fileName = fileUploadRequest.getFileName();			byte [] bytes = fileUploadRequest.getBytes();			FileOutputStream fileOutputStream = new FileOutputStream(new File("D://")+fileName);						fileOutputStream.write(bytes);						fileOutputStream.flush();						fileOutputStream.close();						arg0.write("success");					}else if (arg1 instanceof String )		{			arg0.write("ok do not need to upload file");		}else		{			System.out.println("Receive Error Message");			arg0.write("error");		}	}	public void messageSent(IoSession arg0, Object arg1) throws Exception	{		System.out.println("Being to sent message :" + arg1);	}	public void sessionClosed(IoSession arg0) throws Exception {		System.out.println("Session close");	}	public void sessionCreated(IoSession arg0) throws Exception {		System.out.println("Session create");	}	public void sessionIdle(IoSession arg0, IdleStatus arg1) throws Exception {			}	public void sessionOpened(IoSession arg0) throws Exception	{		System.out.println("Session open");	}}

client:

package mina.example3;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.InputStream;import java.net.InetSocketAddress;import org.apache.mina.core.future.ConnectFuture;import org.apache.mina.core.session.IoSession;import org.apache.mina.filter.codec.ProtocolCodecFilter;import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;import org.apache.mina.filter.logging.LoggingFilter;import org.apache.mina.transport.socket.nio.NioSocketConnector;/** * 文件传输客户端 * @author dujinkai * */public class FileTransClient {	public static void main(String[] args)  throws Exception	{		ObjectSerializationCodecFactory objectSerializationCodecFactory = new ObjectSerializationCodecFactory();		objectSerializationCodecFactory.setDecoderMaxObjectSize(Integer.MAX_VALUE);		objectSerializationCodecFactory.setEncoderMaxObjectSize(Integer.MAX_VALUE);		 //客户端的实现  		 NioSocketConnector connector = new NioSocketConnector();  		 connector.getFilterChain().addLast("codec",  		 new ProtocolCodecFilter(objectSerializationCodecFactory));  		 connector.getFilterChain().addLast("logging", new LoggingFilter());  		 connector.setHandler(new FileClientHandle());  		 		 connector.getSessionConfig().setUseReadOperation(true);  		  		 ConnectFuture cf = connector.connect(new InetSocketAddress("localhost",  		 8998));  		 		 cf.awaitUninterruptibly();  		 IoSession session = cf.getSession(); 		 session.write(getFileUploadRequest());		 		 Object result = session.read().awaitUninterruptibly().getMessage();  		 		 if ("success".equals(result))		 {			 connector.dispose();		 }	}			private static FileUploadRequest getFileUploadRequest() throws Exception	{		FileUploadRequest fileUploadRequest = new FileUploadRequest();				fileUploadRequest.setFileName("djk.jpg");				File file = new File("E://djk.jpg");				InputStream is = new FileInputStream(file);				ByteArrayOutputStream baos = new ByteArrayOutputStream();				byte [] bytes = new byte[1024];				int length = 0; 				while (-1 !=(length = is.read(bytes)))		{			baos.write(bytes, 0, length);		}				fileUploadRequest.setBytes(baos.toByteArray());				is.close();		baos.close();				return fileUploadRequest;	}}

Client Handler:

package mina.example3;import org.apache.mina.core.service.IoHandlerAdapter;import org.apache.mina.core.session.IoSession;public class FileClientHandle extends IoHandlerAdapter{	@Override	public void messageReceived(IoSession session, Object message)			throws Exception 	{		super.messageReceived(session, message);				System.out.println("Result:"+message);	}	@Override	public void messageSent(IoSession session, Object message) throws Exception {				System.out.println("Begin to send Message"+message);		super.messageSent(session, message);	}}

Message:

package mina.example3;import java.io.Serializable;/** * 文件上传对象 * @author dujinkai * */public class FileUploadRequest implements Serializable{	/**	 * 序列号	 */	private static final long serialVersionUID = 1547212123169330600L;		/**	 * 文件名称	 */	private String fileName;		/**	 * 文件字节	 */	private byte [] bytes;	public String getFileName() 	{		return fileName;	}	public void setFileName(String fileName) 	{		this.fileName = fileName;	}	public byte[] getBytes() 	{		return bytes;	}	public void setBytes(byte[] bytes) 	{		this.bytes = bytes;	}	@Override	public String toString() {		return "FileUploadRequest [fileName=" + fileName + "]";	}		}

 

转载于:https://my.oschina.net/boonya/blog/687463

你可能感兴趣的文章
15.二层技术之链路聚合(LACP)-----以太通道
查看>>
不受限字符串函数功能的实现
查看>>
分享40个使用方便的免费智能手机UI套件
查看>>
iOS7重磅推新--不断尝试与重新设计的过程
查看>>
指针实现两数交换和指向函数的指针
查看>>
逗号表达式与自增自减运算符和类型转换的规
查看>>
【安全牛学习笔记】手动漏洞挖掘-SQL注入
查看>>
springboot使用jest操作elasticsearch
查看>>
聊聊hystrix的BucketedCounterStream
查看>>
聊聊rocketmq的RollingFileAppender
查看>>
【学习笔记】Android中Service通信
查看>>
java中时间类(util Date)的后延与前推处理
查看>>
数据链路层的协议分析
查看>>
10月14日笔记
查看>>
JVM01- bin/* 小工具的使用
查看>>
mysql client端安装
查看>>
hbase读写请求详细解释
查看>>
[马哥linux运维][02]
查看>>
老虞学GoLang笔记-字符串
查看>>
C# .net core SHA1CryptoServiceProvider 更新为SHA1.Create()
查看>>