美文网首页
NIO-socket

NIO-socket

作者: wuli白 | 来源:发表于2020-03-29 17:34 被阅读0次

客户端

  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);
            }
        }

    }

相关文章

网友评论

      本文标题:NIO-socket

      本文链接:https://www.haomeiwen.com/subject/toyuuhtx.html