首页 > 应用开发 > Java > Java网络编程与NIO详解2:JAVA NIO 一步步构建IO多路复用的请求模型
// 初始化 socket,建立 socket 与 channel 的绑定关系 SocketChannel socketChannel = SocketChannel.open(); // 初始化远程连接地址 SocketAddress remote = new InetSocketAddress(this.host, port); // I/O 处理设置阻塞,这也是默认的方式,可不设置 socketChannel.configureBlocking(true); // 建立连接 socketChannel.connect(remote);
Socket socket = socketChannel.socket();
PrintWriter pw = getWriter(socketChannel.socket()); BufferedReader br = getReader(socketChannel.socket());
package com.jason.network.mode.nio; import com.jason.network.constant.HttpConstant; import com.jason.network.util.HttpUtil; import java.io.*; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; import java.nio.channels.SocketChannel; public class NioBlockingHttpClient { private SocketChannel socketChannel; private String host; public static void main(String[] args) throws IOException { for (String host: HttpConstant.HOSTS) { NioBlockingHttpClient client = new NioBlockingHttpClient(host, HttpConstant.PORT); client.request(); } } public NioBlockingHttpClient(String host, int port) throws IOException { this.host = host; socketChannel = SocketChannel.open(); socketChannel.socket().setSoTimeout(5000); SocketAddress remote = new InetSocketAddress(this.host, port); this.socketChannel.connect(remote); } public void request() throws IOException { PrintWriter pw = getWriter(socketChannel.socket()); BufferedReader br = getReader(socketChannel.socket()); pw.write(HttpUtil.compositeRequest(host)); pw.flush(); String msg; while ((msg = br.readLine()) != null){ System.out.println(msg); } } private PrintWriter getWriter(Socket socket) throws IOException { OutputStream out = socket.getOutputStream(); return new PrintWriter(out); } private BufferedReader getReader(Socket socket) throws IOException { InputStream in = socket.getInputStream(); return new BufferedReader(new InputStreamReader(in)); } }
import java.nio.channels.Selector; ... private static Selector selector; static { try { selector = Selector.open(); } catch (IOException e) { e.printStackTrace(); } }
SocketChannel socketChannel = SocketChannel.open(); SocketAddress remote = new InetSocketAddress(host, port); // 设置非阻塞模式 socketChannel.configureBlocking(false); socketChannel.connect(remote);
socketChannel.register(selector, SelectionKey.OP_CONNECT | SelectionKey.OP_READ | SelectionKey.OP_WRITE);
// SelectionKey 代表 SocketChannel 在选择器中注册的事件句柄 private void connect(SelectionKey key) throws IOException { // 获取事件句柄对应的 SocketChannel SocketChannel channel = (SocketChannel) key.channel(); // 真正的完成 socket 连接 channel.finishConnect(); // 打印连接信息 InetSocketAddress remote = (InetSocketAddress) channel.socket().getRemoteSocketAddress(); String host = remote.getHostName(); int port = remote.getPort(); System.out.println(String.format("访问地址: %s:%s 连接成功!", host, port)); }
// 字符集处理类 private Charset charset = Charset.forName("utf8"); private void write(SelectionKey key) throws IOException { SocketChannel channel = (SocketChannel) key.channel(); InetSocketAddress remote = (InetSocketAddress) channel.socket().getRemoteSocketAddress(); String host = remote.getHostName(); // 获取 HTTP 请求,同上一篇 String request = HttpUtil.compositeRequest(host); // 向 SocketChannel 写入事件 channel.write(charset.encode(request)); // 修改 SocketChannel 所关心的事件 key.interestOps(SelectionKey.OP_READ); }
private void receive(SelectionKey key) throws IOException { SocketChannel channel = (SocketChannel) key.channel(); ByteBuffer buffer = ByteBuffer.allocate(1024); channel.read(buffer); buffer.flip(); String receiveData = charset.decode(buffer).toString(); // 当再没有数据可读时,取消在选择器中的关联,并关闭 socket 连接 if ("".equals(receiveData)) { key.cancel(); channel.close(); return; } System.out.println(receiveData); }
package com.jason.network.mode.nio; import com.jason.network.constant.HttpConstant; import com.jason.network.util.HttpUtil; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.nio.charset.Charset; import java.util.Iterator; import java.util.Set; public class NioNonBlockingHttpClient { private static Selector selector; private Charset charset = Charset.forName("utf8"); static { try { selector = Selector.open(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) throws IOException { NioNonBlockingHttpClient client = new NioNonBlockingHttpClient(); for (String host: HttpConstant.HOSTS) { client.request(host, HttpConstant.PORT); } client.select(); } public void request(String host, int port) throws IOException { SocketChannel socketChannel = SocketChannel.open(); socketChannel.socket().setSoTimeout(5000); SocketAddress remote = new InetSocketAddress(host, port); socketChannel.configureBlocking(false); socketChannel.connect(remote); socketChannel.register(selector, SelectionKey.OP_CONNECT | SelectionKey.OP_READ | SelectionKey.OP_WRITE); } public void select() throws IOException { while (selector.select(500) > 0){ Set keys = selector.selectedKeys(); Iterator it = keys.iterator(); while (it.hasNext()){ SelectionKey key = (SelectionKey)it.next(); it.remove(); if (key.isConnectable()){ connect(key); } else if (key.isWritable()){ write(key); } else if (key.isReadable()){ receive(key); } } } } private void connect(SelectionKey key) throws IOException { SocketChannel channel = (SocketChannel) key.channel(); channel.finishConnect(); InetSocketAddress remote = (InetSocketAddress) channel.socket().getRemoteSocketAddress(); String host = remote.getHostName(); int port = remote.getPort(); System.out.println(String.format("访问地址: %s:%s 连接成功!", host, port)); } private void write(SelectionKey key) throws IOException { SocketChannel channel = (SocketChannel) key.channel(); InetSocketAddress remote = (InetSocketAddress) channel.socket().getRemoteSocketAddress(); String host = remote.getHostName(); String request = HttpUtil.compositeRequest(host); System.out.println(request); channel.write(charset.encode(request)); key.interestOps(SelectionKey.OP_READ); } private void receive(SelectionKey key) throws IOException { SocketChannel channel = (SocketChannel) key.channel(); ByteBuffer buffer = ByteBuffer.allocate(1024); channel.read(buffer); buffer.flip(); String receiveData = charset.decode(buffer).toString(); if ("".equals(receiveData)) { key.cancel(); channel.close(); return; } System.out.println(receiveData); } }
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69951287/viewspace-2663594/ ,如需转载,请注明出处,否则将追究法律责任。
注册时间:2019-10-19