免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 4012 | 回复: 0
打印 上一主题 下一主题

用NIO实现的一个端口映射的原型 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2005-03-15 21:25 |只看该作者 |倒序浏览
用NIO实现的一个端口映射的原型
  1. /*
  2. * Created on 2004-11-11
  3. */
  4. package niotest;
  5. import java.io.IOException;
  6. import java.net.InetSocketAddress;
  7. import java.nio.ByteBuffer;
  8. import java.nio.channels.SelectionKey;
  9. import java.nio.channels.Selector;
  10. import java.nio.channels.ServerSocketChannel;
  11. import java.nio.channels.SocketChannel;
  12. import java.util.Iterator;
  13. /**
  14. * @author elgs
  15. */
  16. public class Server
  17. {
  18.     private static Selector   selector = null;
  19.     private static ByteBuffer buf      = ByteBuffer.allocateDirect(1024 * 100);
  20.     private static boolean    dbg      = false;
  21.     public static void main(String[] args) throws IOException
  22.     {
  23.         selector = Selector.open();
  24.         ServerSocketChannel ssChannel = ServerSocketChannel.open();
  25.         ssChannel.configureBlocking(false);
  26.         ssChannel.socket().bind(new InetSocketAddress(80));
  27.         ssChannel.register(selector, SelectionKey.OP_ACCEPT);
  28.         System.out.println("Listening on port 80.
  29. ");
  30.         while (selector.select() > 0)
  31.         {
  32.             for (Iterator it = selector.selectedKeys().iterator(); it.hasNext();)
  33.             {
  34.                 // Get the selection key
  35.                 SelectionKey selKey = (SelectionKey) it.next();
  36.                 // Remove it from the list to indicate that it is being
  37.                 // processed
  38.                 it.remove();
  39.                 try
  40.                 {
  41.                     processSelectionKey(selKey);
  42.                 }
  43.                 catch (Exception e)
  44.                 {
  45.                     e.printStackTrace();
  46.                 }
  47.             }
  48.         }
  49.     }
  50.     public static void processSelectionKey(SelectionKey selKey)
  51.             throws IOException
  52.     {
  53.         // Since the ready operations are cumulative,
  54.         // need to check readiness for each operation
  55.         if (selKey.isValid() && selKey.isAcceptable())
  56.         {
  57.             // Get channel with connection request
  58.             ServerSocketChannel ssChannel = (ServerSocketChannel) selKey
  59.                     .channel();
  60.             SocketChannel sChannel = ssChannel.accept();
  61.             sChannel.configureBlocking(false);
  62.             // If serverSocketChannel is non-blocking, sChannel may
  63.             // be null
  64.             if (sChannel != null)
  65.             {
  66.                 SelectionKey clientKey = sChannel.register(selector,
  67.                         SelectionKey.OP_READ | SelectionKey.OP_WRITE);
  68.                 SocketChannel sServerChannel = SocketChannel.open();
  69.                 sServerChannel.configureBlocking(false);
  70.                 sServerChannel.connect(new InetSocketAddress("172.16.31.130",
  71.                         80));
  72.                 //172.16.31.130
  73.                 while (!sServerChannel.finishConnect())
  74.                 {
  75.                     if (dbg)
  76.                         System.out.print(".");
  77.                 }
  78.                 if (dbg)
  79.                     System.out.println("Connected OK!");
  80.                 SelectionKey serverKey = sServerChannel.register(selector,
  81.                         sServerChannel.validOps());
  82.                 clientKey.attach(serverKey);
  83.                 serverKey.attach(clientKey);
  84.             }
  85.         }
  86.         if (selKey.isValid() && selKey.isReadable())
  87.         {
  88.             //          Get channel with bytes to read
  89.             SocketChannel sChannel = (SocketChannel) selKey.channel();
  90.             SelectionKey palKey = (SelectionKey) selKey.attachment();
  91.             if (palKey != null)
  92.             {
  93.                 SocketChannel palChannel = (SocketChannel) palKey.channel();
  94.                 if (palKey.isValid() && selKey.isValid())
  95.                 {
  96.                     // Clear the buffer and read bytes from socket
  97.                     buf.clear();
  98.                     int count = 0;
  99.                     try
  100.                     {
  101.                         while ((count = sChannel.read(buf)) > 0)
  102.                         {
  103.                             buf.flip(); // Make buffer readable
  104.                             while (buf.hasRemaining())
  105.                             {
  106.                                 palChannel.write(buf);
  107.                             }
  108.                             buf.clear();
  109.                         }
  110.                     }
  111.                     catch (IOException e)
  112.                     {
  113.                         sChannel.close();
  114.                         palChannel.close();
  115.                         if (dbg)
  116.                             System.out.println("Forced disconnected!");
  117.                     }
  118.                     if (count == -1)
  119.                     {
  120.                         sChannel.close();
  121.                         palChannel.close();
  122.                         if (dbg)
  123.                             System.out.println("Disconnected OK!");
  124.                     }
  125.                 }
  126.                 else
  127.                 {
  128.                     sChannel.close();
  129.                     palChannel.close();
  130.                     if (dbg)
  131.                         System.out.println("Not Connected!");
  132.                 }
  133.             }
  134.             else
  135.             {
  136.                 sChannel.close();
  137.                 if (dbg)
  138.                     System.out.println("Timeout disconnected OK!");
  139.             }
  140.         }
  141.     }
  142. }
复制代码


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/4960/showart_15791.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP