mina开发udp协议的例子
[b]server端:[/b] [code="java"] 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(); } }[/code] [code="java"]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 { } } [/code] [b]client端:[/b] [code="java"] 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(){ 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(); }[/code] 有2点需要说明: 1.direct和heap buffer。 [code="java"]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. [/code] 下面这2段说的更详细 [code="java"]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. [/code] [code="java"]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).[/code] 2.flip和compact的使用 具体参照代码里的注释,个人理解为,buffer为一个特殊的数组结构,这里理解为一个临时对象tmp,可以任意的put操作,当你认为这些可以作为一个完整的对象发送给udp的另一端的时候,需要结束这些操作把tmp对象转换为buffer。当然如果发送完毕之后你仍要对之前的buffer对象进行put操作,需要执行compact,把它还原为那个tmp临时对象。 最后附一张摘自ibm的mina架构图,帮助理解: [img]/upload/attachment/138644/17bf1b16-d3e0-39b9-8915-79305f19c1b2.bmp[/img]