標籤:關閉 har net config localhost 服務端 package 通道 log
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入門【原】