【说站】SocketChannel在java中实现客户端
2024-10-09
19
SocketChannel在java中实现客户端
1、步骤
(1)创建SocketChannel实例,并将其配置为非阻塞模式,只有在SocketChannel实例中,任何I/O操作都是非阻塞的。
(2)使用connect()方法连接服务器,同时使用while循环连续检测和完全连接。在需要立即进行I/O操作之前,必须使用finishConnect()来完成连接过程。
(3)用ByteBuffer读写字节,假如SelectableChannel是一种非阻塞模式,那么它的I/O操作读写字节可能比实际字节少,甚至没有。因此,我们使用循环连续的读写来确保读写完成。
2、实例
public class NonBlockingTCPClient { public static void main(String[] args) { byte[] data = "hello".getBytes(); SocketChannel channel = null; try { // 1. open a socket channel channel = SocketChannel.open(); // adjust to be nonblocking channel.configureBlocking(false); // 2. init connection to server and repeatedly poll with complete // connect() and finishConnect() are nonblocking operation, both return immediately if (!channel.connect(new InetSocketAddress(InetAddress.getLocalHost(), 8899))) { while (!channel.finishConnect()) { System.out.print("."); } } System.out.println("Connected to server..."); ByteBuffer writeBuffer = ByteBuffer.wrap(data); ByteBuffer readBuffer = ByteBuffer.allocate(data.length); int totalBytesReceived = 0; int bytesReceived; // 3. read and write bytes while (totalBytesReceived < data.length) { if (writeBuffer.hasRemaining()) { channel.write(writeBuffer); } if ((bytesReceived = channel.read(readBuffer)) == -1) { throw new SocketException("Connection closed prematurely"); } totalBytesReceived += bytesReceived; System.out.print("."); } System.out.println("Server said: " + new String(readBuffer.array())); } catch (IOException e) { e.printStackTrace(); } finally { // 4 .close socket channel try { if (channel != null) { channel.close(); } } catch (IOException e) { e.printStackTrace(); } } } }
以上就是SocketChannel在java中实现客户端的方法,希望对大家有所帮助。更多Java学习指路:Java基础
本教程操作环境:windows7系统、java10版,DELL G3电脑。
我的博客即将同步至腾讯云开发者社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=1t7egc96vi6rj
更新于:9天前赞一波!
相关文章
- 【说站】java语言的发展历史
- 【说站】java语言的特点有哪些
- 【说站】java语言属于哪种语言
- 【说站】java语言代码大全
- 【说站】java和c 哪个好
- 【说站】java语言好还是c 好
- 【说站】新手学c还是java
- 【说站】java与c语言区别
- 【说站】java反射三种方法
- 【说站】Java泛型中有几种通配符
- 【说站】Java如何创建类型实例
- 【说站】Java泛型擦除的问题解决
- 【说站】java中Selector如何选择通道
- 【说站】java泛型接口怎么用
- 【说站】java泛型方法的使用注意
- 【说站】java中SocketChannel是什么
- 【说站】Java泛型类如何定义
- 【说站】Java泛型擦除的原理分析
- 【说站】java泛型方法的特征
- java 安全沙箱模型详解
文章评论
评论问答