NIO Socket Server DEMO

1)server端代码

Java代码

  1. /**  
  2.  *   
  3.  * @author Bill
  4.  *  
  5.  */  
  6. public class HelloWorldServer {   
  7.   
  8.     static int BLOCK = 1024;   
  9.     static String name = "";   
  10.     protected Selector selector;   
  11.     protected ByteBuffer clientBuffer = ByteBuffer.allocate(BLOCK);   
  12.     protected CharsetDecoder decoder;   
  13.     static CharsetEncoder encoder = Charset.forName("GB2312").newEncoder();   
  14.   
  15.     public HelloWorldServer(int port) throws IOException {   
  16.         selector = this.getSelector(port);   
  17.         Charset charset = Charset.forName("GB2312");   
  18.         decoder = charset.newDecoder();   
  19.     }   
  20.   
  21.     // 获取Selector   
  22.     protected Selector getSelector(int port) throws IOException {   
  23.         ServerSocketChannel server = ServerSocketChannel.open();   
  24.         Selector sel = Selector.open();   
  25.         server.socket().bind(new InetSocketAddress(port));   
  26.         server.configureBlocking(false);   
  27.         server.register(sel, SelectionKey.OP_ACCEPT);   
  28.         return sel;   
  29.     }   
  30.   
  31.     // 监听端口   
  32.     public void listen() {   
  33.         try {   
  34.             for (;;) {   
  35.                 selector.select();   
  36.                 Iterator iter = selector.selectedKeys().iterator();   
  37.                 while (iter.hasNext()) {   
  38.                     SelectionKey key = (SelectionKey) iter.next();   
  39.                     iter.remove();   
  40.                     process(key);   
  41.                 }   
  42.             }   
  43.         } catch (IOException e) {   
  44.             e.printStackTrace();   
  45.         }   
  46.     }   
  47.   
  48.     // 处理事件   
  49.     protected void process(SelectionKey key) throws IOException {   
  50.         if (key.isAcceptable()) { // 接收请求   
  51.             ServerSocketChannel server = (ServerSocketChannel) key.channel();   
  52.             SocketChannel channel = server.accept();   
  53.             //设置非阻塞模式   
  54.             channel.configureBlocking(false);   
  55.             channel.register(selector, SelectionKey.OP_READ);   
  56.         } else if (key.isReadable()) { // 读信息   
  57.             SocketChannel channel = (SocketChannel) key.channel();   
  58.             int count = channel.read(clientBuffer);   
  59.             if (count > 0) {   
  60.                 clientBuffer.flip();   
  61.                 CharBuffer charBuffer = decoder.decode(clientBuffer);   
  62.                 name = charBuffer.toString();   
  63.                 // System.out.println(name);   
  64.                 SelectionKey sKey = channel.register(selector,   
  65.                         SelectionKey.OP_WRITE);   
  66.                 sKey.attach(name);   
  67.             } else {   
  68.                 channel.close();   
  69.             }   
  70.   
  71.             clientBuffer.clear();   
  72.         } else if (key.isWritable()) { // 写事件   
  73.             SocketChannel channel = (SocketChannel) key.channel();   
  74.             String name = (String) key.attachment();   
  75.                
  76.             ByteBuffer block = encoder.encode(CharBuffer   
  77.                     .wrap("Hello !" + name));   
  78.                
  79.   
  80.             channel.write(block);   
  81.   
  82.             //channel.close();   
  83.   
  84.         }   
  85.     }   
  86.   
  87.     public static void main(String[] args) {   
  88.         int port = 8888;   
  89.         try {   
  90.             HelloWorldServer server = new HelloWorldServer(port);   
  91.             System.out.println("listening on " + port);   
  92.                
  93.             server.listen();   
  94.                
  95.         } catch (IOException e) {   
  96.             e.printStackTrace();   
  97.         }   
  98.     }   
  99. }  
  1.  

     

     

     

     

    server主要是读取client发过来的信息,并返回一条信息

    2)client端代码

    Java代码

    1.   
    2. /**  
    3.  *   
    4.  * @author Bill  
    5.  *  
    6.  */  
    7. public class HelloWorldClient {   
    8.   
    9.     static int SIZE = 10;   
    10.     static InetSocketAddress ip = new InetSocketAddress("localhost", 8888);   
    11.     static CharsetEncoder encoder = Charset.forName("GB2312").newEncoder();   
    12.   
    13.     static class Message implements Runnable {   
    14.         protected String name;   
    15.         String msg = "";   
    16.   
    17.         public Message(String index) {   
    18.             this.name = index;   
    19.         }   
    20.   
    21.         public void run() {   
    22.             try {   
    23.                 long start = System.currentTimeMillis();   
    24.                 //打开Socket通道   
    25.                 SocketChannel client = SocketChannel.open();   
    26.                 //设置为非阻塞模式   
    27.                 client.configureBlocking(false);   
    28.                 //打开选择器   
    29.                 Selector selector = Selector.open();   
    30.                 //注册连接服务端socket动作   
    31.                 client.register(selector, SelectionKey.OP_CONNECT);   
    32.                 //连接   
    33.                 client.connect(ip);   
    34.                 //分配内存   
    35.                 ByteBuffer buffer = ByteBuffer.allocate(8 * 1024);   
    36.                 int total = 0;   
    37.   
    38.                 _FOR: for (;;) {   
    39.                     selector.select();   
    40.                     Iterator iter = selector.selectedKeys().iterator();   
    41.   
    42.                     while (iter.hasNext()) {   
    43.                         SelectionKey key = (SelectionKey) iter.next();   
    44.                         iter.remove();   
    45.                         if (key.isConnectable()) {   
    46.                             SocketChannel channel = (SocketChannel) key   
    47.                                     .channel();   
    48.                             if (channel.isConnectionPending())   
    49.                                 channel.finishConnect();   
    50.                             channel   
    51.                                     .write(encoder   
    52.                                             .encode(CharBuffer.wrap(name)));   
    53.   
    54.                             channel.register(selector, SelectionKey.OP_READ);   
    55.                         } else if (key.isReadable()) {   
    56.                             SocketChannel channel = (SocketChannel) key   
    57.                                     .channel();   
    58.                             int count = channel.read(buffer);   
    59.                             if (count > 0) {   
    60.                                 total += count;   
    61.                                 buffer.flip();   
    62.   
    63.                                 while (buffer.remaining() > 0) {   
    64.                                     byte b = buffer.get();   
    65.                                     msg += (char) b;   
    66.                                        
    67.                                 }   
    68.   
    69.                                 buffer.clear();   
    70.                             } else {   
    71.                                 client.close();   
    72.                                 break _FOR;   
    73.                             }   
    74.                         }   
    75.                     }   
    76.                 }   
    77.                 double last = (System.currentTimeMillis() - start) * 1.0 / 1000;   
    78.                 System.out.println(msg + "used time :" + last + "s.");   
    79.                 msg = "";   
    80.             } catch (IOException e) {   
    81.                 e.printStackTrace();   
    82.             }   
    83.         }   
    84.     }   
    85.   
    86.     public static void main(String[] args) throws IOException {   
    87.        
    88.         String names[] = new String[SIZE];   
    89.   
    90.         for (int index = 0; index < SIZE; index++) {   
    91.             names[index] = "jeff[" + index + "]";   
    92.             new Thread(new Message(names[index])).start();   
    93.         }   
    94.        
    95.     }   
    96. }  

     

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值