ginge 发表于 2013-1-28 19:32:32

一般Socket客户端与Mina NIO Socket客户端对比示例

  在看Mina源代码时发现其客户端Socket Connector的例子很少,耗费了我一些时间。相对传统IO的堵塞式,NIO 的优势和特色就在于非堵塞了。使用NIO的话,不管是服务器端还是客户端,都不用堵住了。这样就大大提高了服务处理的能力,也减少了等待的时间。当然,传统IO Socket编程通常都会使用一个专有线程监听连接请求,获悉新请求后产生其它线程来服务该连接。不管怎么样,这些服务都是同步操作。NIO就不一样了,什么都是通知的。打个比方,就像一个客人到商店预订商品,当商品齐全了,店长就可以将商品发送给客人,或者通知客人取货了。
 
  由于采取了NIO,所以使用Mina时一定要有异步消息处理思想。这里提供一个简单的例子服务器端用传统IO 的ServerSocket,收到新请求后只是返回一个消息:
 
try {                Socket socket = this.serverSocket.accept();                InputStream is = socket.getInputStream();                DataInputStream dis = new DataInputStream(is);                if(dis.read(bytes) < 1024)                {                  System.out.println(new String(bytes));                }                            OutputStream os = socket.getOutputStream();                os.write(("This is server, your reservation number:["+i+"]").getBytes());                os.write(("\nAnything i can help?").getBytes());                os.flush();                os.close();                is.close();                socket.close();            } catch (IOException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }
 

 
 
 
 
 
传统Socket客户端实现:
public void request(byte [] reequest, ResponseHandler handler)    {      if(!socket.isConnected()){            throw new IllegalStateException("Socket not connected to["+address+":"+port+"].");      }      OutputStream os = null;      InputStream is = null;      DataInputStream dis = null;      try {                  os = this.socket.getOutputStream();            os.write(reequest);            os.flush();                is = this.socket.getInputStream();            dis = new DataInputStream(is);                     ByteArrayOutputStream baos = new ByteArrayOutputStream();            byte [] bytes = new byte;            int len = 0;            while((len = dis.read(bytes)) != -1)            {                baos.write(bytes, 0, len);            }                      handler.handleResponse(baos.toByteArray());      } catch (IOException e) {      }finally      {            try {                dis.close();            } catch (IOException e) {             }            try {                os.close();            } catch (IOException e) {            }                   try {                this.socket.close();            } catch (IOException e) {            }      }    } 
 
Mina的Socket Connector方式:
public void test1()    {      try {            final StringBuffer buf = new StringBuffer();            SocketConnector connector = new SocketConnector();            ConnectFuture future = connector.connect(new InetSocketAddress(                  "localhost", 9999), new IoHandlerAdapter() {                public void sessionCreated(IoSession session) {                  log.debug("Session Created");                  buf.append("1");                }                public void sessionOpened(IoSession session) {                  log.debug("Session Opened");                     WriteFuture writeFuture = session.write(ByteBuffer.wrap("Hello".getBytes()));                  writeFuture.join();                }                public void exceptionCaught(IoSession session, Throwable cause) {                  log.debug("Exception,", cause);                  buf.append("X");                }                @Override                public void messageReceived(IoSession session, Object message)                        throws Exception {                           if(message instanceof ByteBuffer)                  {                                             ByteBuffer byteb = (ByteBuffer)message;                        ByteArrayOutputStream baos = new ByteArrayOutputStream();                        byte[] bytearray = new byte;                        while(byteb.hasRemaining())                        {                            int len = Math.min(byteb.remaining(), 1024);                            byteb.get(bytearray,0, len);                            baos.write(bytearray, 0, len);                        }                        log.debug("Message from Server:" + new String(baos.toByteArray()));                  }                                 }                @Override                public void messageSent(IoSession session, Object message)                        throws Exception {                  log.debug("Sent:" + message);                }                @Override                public void sessionClosed(IoSession session) throws Exception {                  log.debug("Session closed.");                  super.sessionClosed(session);                }                @Override                public void sessionIdle(IoSession session, IdleStatus status)                        throws Exception {                  // TODO Auto-generated method stub                  super.sessionIdle(session, status);                }            });            log.debug("connect future join begin.");//等待连接准备            future.join();            log.debug("connect future join end.");               CloseFuture closeFuture = future.getSession().close();            log.debug("close future join begin.");            closeFuture.join();            log.debug("close future join end.");      }catch(Exception e)      {            e.printStackTrace();      }    } 
页: [1]
查看完整版本: 一般Socket客户端与Mina NIO Socket客户端对比示例