原创

NIO实现tcp服务端客户端通信

  1. 服务端
    ```
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.net.ServerSocket;
    import java.nio.ByteBuffer;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.ServerSocketChannel;
    import java.nio.channels.SocketChannel;
    import java.util.Iterator;
    import java.util.Set;
    /**
  2. @author CXL
  3. @version 创建时间:2018年12月4日 下午2:05:43
  4. 类说明
    */
    public class NioServer {
    public static void main(String[] args) throws IOException {

      //开启选择器
      Selector selector=Selector.open();
      ServerSocketChannel ssChannel = ServerSocketChannel.open();
      ssChannel.configureBlocking(false);
      //注册选择器
      ssChannel.register(selector, SelectionKey.OP_ACCEPT);
      ServerSocket serverSocket = ssChannel.socket();
      InetSocketAddress address = new InetSocketAddress("127.0.0.1",8888);
      serverSocket.bind(address);
      while (true) {
          selector.select();
          Set<SelectionKey> keys = selector.selectedKeys();
    
          Iterator<SelectionKey> keyIterator = keys.iterator();
          while(keyIterator.hasNext()) {
              SelectionKey keyIt = keyIterator.next();
              if (keyIt.isAcceptable()) {
                  ServerSocketChannel ssChannel1 = (ServerSocketChannel) keyIt.channel();
                  //服务器会为每个新连接创建一个SockerChannel
                  SocketChannel sChannel = ssChannel1.accept();
                  sChannel.configureBlocking(false);
                  //这个新连接主要用于从客户端读取数据
                  sChannel.register(selector,SelectionKey.OP_READ);
              }else if (keyIt.isReadable()) {
                  SocketChannel sChannel = (SocketChannel) keyIt.channel();
                  System.out.println(readDataFromSockertChannel(sChannel));
                  sChannel.close();
              }
              keyIterator.remove();
          }
      }
    

    }
    private static String readDataFromSockertChannel(SocketChannel sChannel) throws IOException {

      ByteBuffer buffer = ByteBuffer.allocate(1024);
      StringBuilder data = new StringBuilder();
      while (true) {
           buffer.clear();
           int n = sChannel.read(buffer);
           if (n == -1) {
              break;
          }
           buffer.flip();
           int limit = buffer.limit();
          char[] dst = new char[limit];
          for (int i = 0; i < limit; i++) {
              dst[i] = (char) buffer.get(i);
          }
          data.append(dst);
          buffer.clear();
    
      }
       return data.toString();        
    

    }

}

2.客户端

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

/**

  • @author CXL
  • @version 创建时间:2018年12月4日 下午2:37:52
  • 类说明
    */
    public class NIOClient {
    public static void main(String[] args) throws IOException {

      Socket socket = new Socket("127.0.0.1", 8888);
      OutputStream out = socket.getOutputStream();
      String string = "hello world!";
      out.write(string.getBytes());
      out.close();
    

    }

}
```

正文到此结束
Loading...