NIO核心组件 - Channel
SocketChannel 和 ServerSocketChannel
学习此部分可以对比Socket和ServerSocket
服务端代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| public class NioSocketServer01 { public static void main(String[] args) { try { ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.configureBlocking(false); serverSocketChannel.socket().bind(new InetSocketAddress(8080)); while (true) { SocketChannel socketChannel = serverSocketChannel.accept(); if (socketChannel != null) { ByteBuffer buffer = ByteBuffer.allocate(1024); socketChannel.read(buffer); System.err.println(new String(buffer.array())); buffer.flip(); socketChannel.write(buffer);
} else { Thread.sleep(1000L); System.err.println("no client"); } }
} catch (IOException | InterruptedException e) { e.printStackTrace(); } } }
|
客户端代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| public class NioSocketClient1 { public static void main(String[] args) { try { SocketChannel socketChannel = SocketChannel.open(); socketChannel.configureBlocking(false); socketChannel.connect(new InetSocketAddress("localhost", 8080)); if (socketChannel.isConnectionPending()) { socketChannel.finishConnect(); }
ByteBuffer byteBuffer = ByteBuffer.allocate(1024); byteBuffer.put("hello world".getBytes()); byteBuffer.flip(); socketChannel.write(byteBuffer); byteBuffer.clear(); int r = socketChannel.read(byteBuffer); if (r > 0) { System.out.println("get msg:{}" + new String(byteBuffer.array())); } else { System.out.println("server no back"); } } catch (IOException e) { e.printStackTrace(); } } }
|