NIO-socket

2020-03-29  本文已影响0人  wuli白

客户端

  public static void main(String[] args) throws IOException, InterruptedException {

      SocketChannel socketChannel = SocketChannel.open();

      socketChannel.connect(new InetSocketAddress("127.0.0.1", 8000));

      socketChannel.configureBlocking(false);

      while (!socketChannel.finishConnect()) {
          System.out.println("do some ");
      }

      ByteBuffer byteBuffer = ByteBuffer.allocate("Hello World channel".getBytes().length);

      byteBuffer.put("Hello World channel".getBytes());

      byteBuffer.flip();
      while (byteBuffer.hasRemaining()) {
          socketChannel.write(byteBuffer);
      }
  }

服务端

public static void main(String[] args) throws IOException {

        ServerSocketChannel channel = ServerSocketChannel.open();
        channel.bind(new InetSocketAddress("127.0.0.1", 8000));
        channel.configureBlocking(false);
        while (true) {

            list.forEach(socket -> {
                try {
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                    socket.configureBlocking(false);

                    int read = socket.read(byteBuffer);
                    if (read > 0) {
                        byteBuffer.flip();
                        byte[] bytes = new byte[read];
                        byteBuffer.get(bytes);
                        System.out.println(new String(bytes));
                        byteBuffer.flip();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });

            SocketChannel socketChannel = channel.accept();
            if (socketChannel != null) {
                list.add(socketChannel);
            }
        }

    }
上一篇 下一篇

猜你喜欢

热点阅读