java mina 文件_初识java之Mina(一)

Apache Mina Server 是一个网络通信应用框架,也就是说,它主要是对基于 TCP/IP、UDP/IP协议栈的通信框架(当然,也可以提供 JAVA 对象的序列化服务、虚拟机管道通信服务等),Mina 可以帮助我们快速开发高性能、高扩展性的网络通信应用,Mina 提供了事件驱动、异步(Mina 的异步 IO 默认使用的是 JAVA NIO 作为底层支持)操作的编程模型。

首先先写个简单的server,来实现异步的文件上传。

public class Main {

private static final int PORT = 8080;

public static void main(String[] args) throws Exception {

NioSocketAcceptor accept = new NioSocketAcceptor();

accept.getFilterChain().addLast("codec",

new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));

accept.getFilterChain().addLast("logging", new LoggingFilter());

accept.setHandler(new FileUploadHandler());

accept.bind(new InetSocketAddress(PORT));

System.out.println("upload server started.");

}

}

handle的处理就狠简单了。

public class FileUploadHandler extends IoHandlerAdapter {

private BufferedOutputStream out;

private int count;

private static final Log log = LogFactory.getLog(FileUploadHandler.class);

public void sessionOpened(IoSession session) throws Exception {

System.out.println("server open");

public void exceptionCaught(IoSession session, Throwable cause)

throws Exception {

System.out.println("exception");

session.close(true);

super.exceptionCaught(session, cause);

}

public void messageReceived(IoSession session, Object message) {

System.out.println("server received");

try {

if (message instanceof FileUploadRequest) {

FileUploadRequest request = (FileUploadRequest) message;

System.out.println(request.getFilename());

if (out == null) {

String [] array = request.getFilename().split("//");

System.out.println(array[1]);

out = new BufferedOutputStream(new FileOutputStream("D://"+array[1]));

out.write(request.getFileContent());

} else {

out.write(request.getFileContent());

}

count += request.getFileContent().length;

} else if (message instanceof String) {

if (((String) message).equals("finish")) {

System.out.println("size is " + count);

out.flush();

out.close();

out = null;

session.write("success");

}

}

} catch (Exception e) {

e.printStackTrace();

}

}

public void sessionClosed(IoSession session) throws Exception {

System.out.println("server session close");

}

}


版权声明:本文为weixin_31642161原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。