server端:
void UdpServerByMina(int port){
acceptor=new NioDatagramAcceptor();
acceptor.setHandler(new ChatUdpServerHandler());
//can use that port next again
//acceptor.getSessionConfig().setReuseAddress(true);
DefaultIoFilterChainBuilder chain=acceptor.getFilterChain();
chain.addLast("logger", new LoggingFilter());
try {
acceptor.bind(new InetSocketAddress(port));
} catch (IOException e) {
e.printStackTrace();
}
}
public class ChatUdpServerHandler implements IoHandler {
public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
cause.printStackTrace();
session.close(false);
}
//some service handle
public void messageReceived(IoSession session, Object message) throws Exception {
if(message instanceof IoBuffer){
IoBuffer buffer=(IoBuffer)message;
Command command=Command.getCommand(buffer,(InetSocketAddress)session.getRemoteAddress());
if(command!=null)
command.execute();
}
}
public void messageSent(IoSession session, Object message) throws Exception {
}
public void sessionClosed(IoSession session) throws Exception {
}
public void sessionCreated(IoSession session) throws Exception {
}
public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
}
public void sessionOpened(IoSession session) throws Exception {
}
}
client端:
public void send(InetAddress addr,int port,final byte[] data){
IoConnector connector=new NioDatagramConnector();
connector.setHandler(new ChatUdpClientHandler());
ConnectFuture future=connector.connect(new InetSocketAddress(addr.getHostAddress(),port));
future.awaitUninterruptibly();
future.addListener(new IoFutureListener<ConnectFuture>(){
public void operationComplete(ConnectFuture future) {
if (future.isConnected()) {
ioSession = future.getSession();
/*
* this is just for heap buffer.
* if true derict buffer will be returned , and then it cannot be gc.
* easy to OOM exception
*/
IoBuffer buffer = IoBuffer.allocate(data.length,false);
buffer.put(data);
/*
* Flips this buffer.
* The limit is set to the current position and then the position is set to zero.
* If the mark is defined then it is discarded
* This method is often used in conjunction with the compact method when transferring data from one place to another.
* @see Buffer#compact
*/
buffer.flip();
//buffer.compact();
//buffer.put(someobj);
//buffer.flip();
ioSession.write(buffer);
} else {
System.out.println("Not connected...exiting");
}
}
});
future.cancel();
//future.getSession().getCloseFuture().awaitUninterruptibly();
}
有2点需要说明:
1.direct和heap buffer。
Direct Byte Buffer [ByteBuffer.allocateDirect()]: Given a direct byte buffer, the Java virtual machine will make a best effort to perform native I/O operations directly upon it.
Heap Byte Buffer [ByteBuffer.allocate()]: A byte buffer backed by a byte array.
View Byte Buffer [ByteBuffer.slice()]: a byte buffer whose content is a shared subsequence of direct or heap byte buffer's content.
下面这2段说的更详细
Utilities for direct (native) buffers. Unlike arrays and non-direct buffers that are backed by arrays, the contents of direct buffers cannot move during garbage-collection. This makes direct buffers useful in systems (e.g., OpenGL) that require native pointers to memory.
Memory allocated for a direct buffer typically lies outside the garbage-collected Java heap. That memory is freed when the direct buffer is garbage collected. Unfortunately, garbage collection normally occurs when insufficient space is available inside the Java heap. If insufficient space outside the Java heap is available, then allocation of a new direct buffer may fail with a OutOfMemoryError. This error may occur because direct buffers that are garbage have not yet been collected, perhaps because plenty of space is available inside the Java heap.
A solution to this problem is to perform garbage collection when this error occurs. Normally, a OutOfMemoryError is fatal. However, methods in this class that allocate direct buffers will catch this error and call System.gc() before attempting to allocate the buffer a second time. If that second attempt fails, then no further attempts are made and the error is thrown again. There is no guarantee that this solution will work, but we have not yet seen it fail in tests that repeatedly allocate direct buffers that quickly become garbage.
One reason why MappedByteBuffer can be faster is that it can be based on a 'Direct' ByteBuffer.
When a ByteBuffer is 'Direct', the bytes behind it are allocated outside the JVM in an OS specific manner and can be directly accessed by OS input/output calls. By doing this a whole set of OS specific file calls can be easily used that were not necessarily used by older JVMs (this can include OS specific buffering calls that are supported in hardware).
2.flip和compact的使用
具体参照代码里的注释,个人理解为,buffer为一个特殊的数组结构,这里理解为一个临时对象tmp,可以任意的put操作,当你认为这些可以作为一个完整的对象发送给udp的另一端的时候,需要结束这些操作把tmp对象转换为buffer。当然如果发送完毕之后你仍要对之前的buffer对象进行put操作,需要执行compact,把它还原为那个tmp临时对象。
最后附一张摘自ibm的mina架构图,帮助理解:
- 大小: 101.6 KB
分享到:
相关推荐
最近做rfid读写,C#和java都用udp不用厂家的动态库,udp自己写也简单,但是试了一下Apache mina ,接收的不是string,二十byte[] 数组,简单实现了UDP,网上也有例子,但是不是我要的。可用。
望大家不吝批评指教,本人常年从事JAVA软件开发,有丰富的MINA通信软件开发经验,现在已经有成熟的底层框架(结合了反射、DynaBean、Spring等多种技术),可以实现程序自动对上位机和下位机之间的通信协议进行解析,...
mina实现UDP协议的代码,学习Mina的可以研究一下,对学习有好处的
收集几个mina的通讯例子,实现TCP、UDP通讯
Android Mina UDP数据交互。 资源提供客户端为Android 工程,服务端为普通的Java工程的数据交互示例。
资源提供Android Mina UDP 所需jar包
一个mina的可运行的udp demo(java工程),自己根据网上的资源整合的,包括一个客户端和一个服务器,非常适合新手入门
最近使用Mina开发一个Java的NIO服务端程序,因此也特意学习了Apache的这个Mina框架。...它提供了一个抽象的、事件驱动的异步API,使Java NIO在各种传输协议(如TCP/IP,UDP/IP协议等)下快速高效开发
本源码是《NIO框架入门(三):iOS与MINA2、Netty4的跨平台UDP双向通信实战》一文的服务端实现(MINA2版),详见:http://www.52im.net/thread-378-1-1.html
本源码是《NIO框架入门(二):服务端基于MINA2的UDP双向通信Demo演示》一文的MINA2服务端源码实现,详见:http://www.52im.net/thread-373-1-1.html
Apache Mina Server 是一个网络通信应用框架,也就是说,它主要是对基于TCP/IP、UDP/IP 协议栈的通信框架(当然,也可以提供JAVA 对象的序列化服务、虚拟机管道通信服务等), Mina 可以帮助我们快速开发高性能、高...
服务端为mina 本地环境内网已测通。 测试环境为内网连接公网,公网连接公网可通。 如果测试不通 1.请检查端口服务类型(服务端端口是TCP/UDP)。 2.检查网络环境。 3.默认回车换行断包。所以注意发送内容后面...
Mina自定义协议通信的示例
本源码是《NIO框架入门(二):服务端基于MINA2的UDP双向通信Demo演示》一文的Java客户端源码实现,详见:http://www.52im.net/thread-373-1-1.html
Mina开发之客户端的代码,详情请查看:http://www.cnblogs.com/getherBlog/p/3937196.html
mina仿qq聊天功能,自定义协议,协议的编码和...mina聊天 mina解码编码 mina协议开发 mina仿qq mina消息xml mina开发的在线聊天工具,mina仿qq功能,mina自定义协议,可以仿http请求,mina心跳等技术大全,mina功能大揭密
mina通信协议文档及实例,内含说明文档及实例,长短连接
基于MINA架构实现的UDP接收服务器,支持对mysql数据库的连接池插入查找操作。数据接收采用MINA,处理使用线程池并结合数据库连接池实现对发送数据的储存。
公司需求,做的简单的Demo,可以拓展,Mina自定义协议简单实现,象征性得收取2积分
Mina开发之服务器的代码,详情请查看:http://www.cnblogs.com/getherBlog/p/3937196.html Mina开发之客户端的代码,详情请查看:http://www.cnblogs.com/getherBlog/p/3937196.html