Commit 279e4b707d1022f19716f6d63ba1e67019e29757

Authored by hanshaofeng
1 parent 6adfb8fe6d

nio server

Showing 2 changed files with 107 additions and 10 deletions

platform-operate-api/src/main/java/com/lyms/hospitalapi/NIOServer.java View file @ 279e4b7
... ... @@ -99,21 +99,26 @@
99 99 * @param key
100 100 * @throws IOException
101 101 */
102   - public int read(SelectionKey key) throws IOException{
  102 + public int read(SelectionKey key) {
103 103 // 服务器可读取消息:得到事件发生的Socket通道
104 104 SocketChannel channel = (SocketChannel) key.channel();
105 105 // 创建读取的缓冲区
106   - ByteBuffer buffer = ByteBuffer.allocate(10);
107   - channel.read(buffer);
108   - byte[] data = buffer.array();
109   - String msg = new String(data).trim();
110   - if (msg.length() == 0) {
  106 + try {
  107 + ByteBuffer buffer = ByteBuffer.allocate(10);
  108 + channel.read(buffer);
  109 + byte[] data = buffer.array();
  110 + String msg = new String(data).trim();
  111 + if (msg.length() == 0) {
  112 + return 0;
  113 + }
  114 + System.out.println("服务端收到信息:" + msg);
  115 + ByteBuffer outBuffer = ByteBuffer.wrap("success".getBytes());
  116 + channel.write(outBuffer);// 将消息回送给客户端
  117 + return msg.length();
  118 + } catch (Exception e) {
  119 + e.printStackTrace();
111 120 return 0;
112 121 }
113   - System.out.println("服务端收到信息:"+msg);
114   - ByteBuffer outBuffer = ByteBuffer.wrap("success".getBytes());
115   - channel.write(outBuffer);// 将消息回送给客户端
116   - return msg.length();
117 122 }
118 123  
119 124 class BeatTask extends Thread {
platform-operate-api/src/main/java/com/lyms/hospitalapi/NioClient.java View file @ 279e4b7
... ... @@ -5,6 +5,15 @@
5 5  
6 6 import javax.annotation.PostConstruct;
7 7 import java.io.IOException;
  8 +import java.net.InetSocketAddress;
  9 +import java.nio.ByteBuffer;
  10 +import java.nio.channels.SelectionKey;
  11 +import java.nio.channels.Selector;
  12 +import java.nio.channels.SocketChannel;
  13 +import java.nio.charset.Charset;
  14 +import java.util.Iterator;
  15 +import java.util.Scanner;
  16 +import java.util.Set;
8 17  
9 18 /**
10 19 * Created by riecard on 2016/11/24.
11 20  
12 21  
... ... @@ -14,10 +23,93 @@
14 23  
15 24 public static final String NIO_CLIENT_START = PropertiesUtils.getPropertyValue("nio_client_start");
16 25  
  26 + private Selector selector = null;
  27 + static final int port = 8000;
  28 + private Charset charset = Charset.forName("UTF-8");
  29 + private SocketChannel sc = null;
  30 + private String name = "";
  31 + private static String USER_EXIST = "system message: user exist, please change a name";
  32 + private static String USER_CONTENT_SPILIT = "#@#";
  33 +
17 34 @PostConstruct
18 35 public void init() throws IOException {
19 36 if ("1".equals(NIO_CLIENT_START)) {
20 37 }
  38 + selector = Selector.open();
  39 + //连接远程主机的IP和端口
  40 + sc = SocketChannel.open(new InetSocketAddress("192.168.5.250",port));
  41 + sc.configureBlocking(false);
  42 + sc.register(selector, SelectionKey.OP_READ);
  43 + //开辟一个新线程来读取从服务器端的数据
  44 + new Thread(new ClientThread()).start();
  45 + //在主线程中 从键盘读取数据输入到服务器端
  46 + Scanner scan = new Scanner(System.in);
  47 + while(scan.hasNextLine())
  48 + {
  49 + String line = scan.nextLine();
  50 + if("".equals(line)) continue; //不允许发空消息
  51 + if("".equals(name)) {
  52 + name = line;
  53 + line = name+USER_CONTENT_SPILIT;
  54 + } else {
  55 + line = name+USER_CONTENT_SPILIT+line;
  56 + }
  57 + sc.write(charset.encode(line));//sc既能写也能读,这边是写
  58 + }
21 59 }
  60 +
  61 + private class ClientThread implements Runnable
  62 + {
  63 + public void run()
  64 + {
  65 + try
  66 + {
  67 + while(true) {
  68 + int readyChannels = selector.select();
  69 + if(readyChannels == 0) continue;
  70 + Set selectedKeys = selector.selectedKeys(); //可以通过这个方法,知道可用通道的集合
  71 + Iterator keyIterator = selectedKeys.iterator();
  72 + while(keyIterator.hasNext()) {
  73 + SelectionKey sk = (SelectionKey) keyIterator.next();
  74 + keyIterator.remove();
  75 + dealWithSelectionKey(sk);
  76 + }
  77 + }
  78 + }
  79 + catch (IOException io)
  80 + {}
  81 + }
  82 +
  83 + private void dealWithSelectionKey(SelectionKey sk) throws IOException {
  84 + if(sk.isReadable())
  85 + {
  86 + //使用 NIO 读取 Channel中的数据,这个和全局变量sc是一样的,因为只注册了一个SocketChannel
  87 + //sc既能写也能读,这边是读
  88 + SocketChannel sc = (SocketChannel)sk.channel();
  89 +
  90 + ByteBuffer buff = ByteBuffer.allocate(1024);
  91 + String content = "";
  92 + while(sc.read(buff) > 0)
  93 + {
  94 + buff.flip();
  95 + content += charset.decode(buff);
  96 + }
  97 + //若系统发送通知名字已经存在,则需要换个昵称
  98 + if(USER_EXIST.equals(content)) {
  99 + name = "";
  100 + }
  101 + System.out.println(content);
  102 + sk.interestOps(SelectionKey.OP_READ);
  103 + }
  104 + }
  105 + }
  106 +
  107 +
  108 +
  109 + public static void main(String[] args) throws IOException
  110 + {
  111 + new NioClient().init();
  112 + }
  113 +
22 114 }