🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
~~~ package com.youge.nio.client; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; /** * @author: hcf * @qq: 46914685 * @email: 46914685@qq.com * @date: 2020/11/26 13:37 */ 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 尚硅谷~"; //Wraps a byte array into a buffer. ByteBuffer buffer = ByteBuffer.wrap(str.getBytes()); //发送数据,将buffer数据写入channel socketChannel.write(buffer); System.in.read(); } } ~~~