NIO实现客户端、服务端

NIO实现服务端

NIO实现客户端

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

/**
* @description: NIOClient
* @author TAO
* @date 2021/6/27 23:57
*/
public class NIOClient {
          
   

    public static void main(String[] args) throws IOException {
          
   
        //得到一个网络通道
        SocketChannel socketChannel = SocketChannel.open();

        //设置为非阻塞
        socketChannel.configureBlocking(false);

        //根据服务端的ip和端口
        InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 6666);

        //连接服务器
        if (!socketChannel.connect(inetSocketAddress)){
          
   

            while (!socketChannel.finishConnect()){
          
   
                System.out.println("因为连接需要时间,客户端不会阻塞,可以做其他操作...");
            }
        }

        //如果连接成功,就发送数据
        String str = "hello";
        ByteBuffer buffer = ByteBuffer.wrap(str.getBytes());
        //发送数据,将buffer数据写入channel
        socketChannel.write(buffer);
        System.in.read();
    }
}
经验分享 程序员 微信小程序 职场和发展