其他分享
首页 > 其他分享> > NIO之SocketChannel

NIO之SocketChannel

作者:互联网

1、服务端

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class ServerSocketChannelDemo {
  public static void main(String[] args) throws IOException {
    //端口号
    int port = 8888;
    //buffer
    ByteBuffer buffer = ByteBuffer.wrap("hello atguigu".getBytes());
    //ServerSocketChannel
    ServerSocketChannel ssc = ServerSocketChannel.open();
    //绑定
    ssc.socket().bind(new InetSocketAddress(port));
    //设置非阻塞模式
    ssc.configureBlocking(true);
    //监听是否有新的连接传入
    while (true) {
      System.out.println("Waiting for connections");
      SocketChannel sc = ssc.accept();
      if (sc == null) {
        System.out.println("null");
      } else {
        System.out.println("Incoming connection from: " + sc.socket().getRemoteSocketAddress());
        buffer.rewind();//指针0
        sc.write(buffer);
        sc.close();
      }
    }
  }
}

2、客户端

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class SocketChannelDemo {
  public static void main(String[] args) throws IOException {
    SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 8888));
    // 测试SocketChannel是否为open状态
    System.out.println("是否为open状态:" + socketChannel.isOpen());
    //测试SocketChannel是否已经被连接
    System.out.println("是否已连接:" + socketChannel.isConnected());
    //测试SocketChannel是否正在进行连接
    System.out.println("是否正在连接:" + socketChannel.isConnectionPending());
    //校验正在进行套接字连接的SocketChannel是否已经完成连接
    System.out.println("是否已完成连接:" + socketChannel.finishConnect());

    socketChannel.configureBlocking(false);
    ByteBuffer byteBuffer = ByteBuffer.allocate(16);


    int bytesRead = socketChannel.read(byteBuffer);
    while (bytesRead != -1) {
      System.out.println("读取:" + bytesRead);
      byteBuffer.flip();
      while (byteBuffer.hasRemaining()) {
        System.out.print((char) byteBuffer.get());
      }
      byteBuffer.clear();
      bytesRead = socketChannel.read(byteBuffer);
    }

    socketChannel.close();

    System.out.println("read over");

  }
}

标签:NIO,System,socketChannel,println,import,SocketChannel,out
来源: https://www.cnblogs.com/xl4ng/p/15915183.html