1、步骤
(1)创建SocketChannel实例,并将其配置为非阻塞模式,只有在SocketChannel实例中,任何I/O操作都是非阻塞的。
(2)使用connect()方法连接服务器,同时使用while循环连续检测和完全连接。在需要立即进行I/O操作之前,必须使用finishConnect()来完成连接过程。
(3)用ByteBuffer读写字节,假如SelectableChannel是一种非阻塞模式,那么它的I/O操作读写字节可能比实际字节少,甚至没有。因此,我们使用循环连续的读写来确保读写完成。
2、实例
publicclassNonBlockingTCPClient{ publicstaticvoidmain(String[]args){ byte[]data="hello".getBytes(); SocketChannelchannel=null; try{ //1.openasocketchannel channel=SocketChannel.open(); //adjusttobenonblocking channel.configureBlocking(false); //2.initconnectiontoserverandrepeatedlypollwithcomplete //connect()andfinishConnect()arenonblockingoperation,bothreturnimmediately if(!channel.connect(newInetSocketAddress(InetAddress.getLocalHost(),8899))){ while(!channel.finishConnect()){ System.out.print("."); } } System.out.println("Connectedtoserver..."); ByteBufferwriteBuffer=ByteBuffer.wrap(data); ByteBufferreadBuffer=ByteBuffer.allocate(data.length); inttotalBytesReceived=0; intbytesReceived; //3.readandwritebytes while(totalBytesReceived<data.length){ if(writeBuffer.hasRemaining()){ channel.write(writeBuffer); } if((bytesReceived=channel.read(readBuffer))==-1){ thrownewSocketException("Connectionclosedprematurely"); } totalBytesReceived+=bytesReceived; System.out.print("."); } System.out.println("Serversaid:"+newString(readBuffer.array())); }catch(IOExceptione){ e.printStackTrace(); }finally{ //4.closesocketchannel try{ if(channel!=null){ channel.close(); } }catch(IOExceptione){ e.printStackTrace(); } } } }
以上就是SocketChannel在java中实现客户端的方法,希望对大家有所帮助。更多Java学习指路:Java基础
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
暂无评论内容