2.java nio 网络编程 client端
程序员文章站
2022-03-20 20:53:41
...
前面写了nio 网络 server端,这里是client端,只写了简单的发送接收数据,最后关闭连接。大文本发送和接手参考server端写法就行了。
不过这里有个异常,客户端这边调用socketChannel的close方法以后,服务端继续使用这个channel的话,会抛出异常。所以在server端需要检查,socketChannel.read(rb)这个方法会返回一个整数,当返回的数大于-1的时候,表示这个socketChannel没有close,当socketChannel调用close方法以后,会返回-1,这时候,就不要操作这个socketChannel还有不要调用SelectionKey的interestOps方法,这里面也会用到这个socketChannel。
package com.govert.project; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.util.Set; /** * Created by govert on 2016/8/21. */ public class NioClient { public static void main(String[] args) throws IOException { // read and write byte buffer ByteBuffer rb = ByteBuffer.allocate(1024); ByteBuffer wb = ByteBuffer.allocate(1024); // connect hostname and port String hostname = "127.0.0.1"; int port = 9000; // open Selector & check Selector selector = Selector.open(); if (selector.isOpen()) { System.err.println("Selector open success."); } // open SocketChannel & check SocketChannel socketChannel = SocketChannel.open(); if (socketChannel.isOpen()) { System.err.println("SocketChannel open success."); } // config non-block & connect socketChannel.configureBlocking(false); socketChannel.connect(new InetSocketAddress(hostname, port)); // socketChannel register selector socketChannel.register(selector, SelectionKey.OP_CONNECT); // hand event loop boolean isExit = false; while (!isExit) { selector.select(); Set<SelectionKey> keys = selector.selectedKeys(); for (SelectionKey key : keys) { if (key.isReadable()) { rb.clear(); socketChannel.read(rb); rb.flip(); System.err.println(new String(rb.array(), 0, rb.limit(), "utf-8")); // key.interestOps(SelectionKey.OP_WRITE); // key.cancel(); socketChannel.close(); isExit = true; } else if (key.isWritable()) { String req = "hello server, i am from client."; wb.clear(); wb.put(req.getBytes("utf-8")); wb.flip(); socketChannel.write(wb); key.interestOps(SelectionKey.OP_READ); } else if (key.isConnectable()) { socketChannel.finishConnect(); System.err.println("client connect server success."); key.interestOps(SelectionKey.OP_WRITE); } } // keys.clear(); } } }
上一篇: js怎么设置css高度