java NIO入门原
Posted 万物生长
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java NIO入门原相关的知识,希望对你有一定的参考价值。
server
package com.server; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; public class Server { public static void main(String[] args) throws Exception { //新建TCP服务端 ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); //绑定TCP端口 serverSocketChannel.socket().bind(new InetSocketAddress(9999)); //配置成"非阻塞" serverSocketChannel.configureBlocking(false); while (true) { //允许接收TCP链接 SocketChannel socketChannel = serverSocketChannel.accept(); //当有TCP连接上来时,获取到的就不为空 if (socketChannel != null) { //写英文数据"生命不步,战斗不息" String newData = System.currentTimeMillis() + ": Cease to struggle and you cease to live ."; //开辟缓存 ByteBuffer buf = ByteBuffer.allocate(1024); //重置,准备写入数据到缓存 buf.clear(); //真正写入数据到缓存 buf.put(newData.getBytes()); //准备从缓存读取数据 buf.flip(); //如果读到数据有剩余 while (buf.hasRemaining()) { //真正从缓存读取数据,并写入到通道中 socketChannel.write(buf); } } } } }
client
package com.client; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; public class client { public static void main(String[] args) throws Exception { //新建TCP服务端 SocketChannel socketChannel = SocketChannel.open(); //链接到本地的8888端口 socketChannel.connect(new InetSocketAddress("localhost", 8888)); //开辟缓存 ByteBuffer buf = ByteBuffer.allocate(1024); //重置,准备写入数据到缓存 buf.clear(); //真正从通道读取数据到缓存 int bytesRead = socketChannel.read(buf); //准备从缓存读取数据 buf.flip(); //如果读到数据有剩余 while (buf.hasRemaining()) { //取一个字节 byte b = (byte) (buf.get()); //转成一个字符 System.out.print((char) b); } //关闭通道 socketChannel.close(); } }
以上是关于java NIO入门原的主要内容,如果未能解决你的问题,请参考以下文章