Java -- NIO-TCP Socket, java -- nio-tcp
1. First, we use SocketChannel to implement the socket Client.
package com.seeyon.nio.socket;import java.io.IOException;import java.net.InetSocketAddress;import java.nio.ByteBuffer;import java.nio.channels.SocketChannel;/** * Created by yangyu on 2017/2/22. */public class Client { public static void main(String[] args) { try (SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("localhost", 8088))) { socketChannel.configureBlocking(false); ByteBuffer byteBuffer = ByteBuffer.allocate(512); socketChannel.write(ByteBuffer.wrap("this is client send message".getBytes())); while (true) { byteBuffer.clear(); int readBytes = socketChannel.read(byteBuffer); if (readBytes > 0) { byteBuffer.flip(); System.out.println(new String(byteBuffer.array(), 0, readBytes)); socketChannel.close(); break; } } } catch (IOException e) { e.printStackTrace(); } }}
2. Use ServerSocketChannel to implement the server, and use Selector
Package com. seeyon. nio. socket; 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. serverSocketChannel; import java. nio. channels. socketChannel; import java. util. iterator; import java. util. set;/*** Created by yangyu on April /2/22. */public class Server {public static void main (String [] args) throws IOException {ServerSocketChannel serverChannel = ServerSocketChannel. open (); serverChannel. socket (). bind (new InetSocketAddress (8088); serverChannel. configureBlocking (false); Selector selector = Selector. open (); serverChannel. register (selector, SelectionKey. OP_ACCEPT); while (true) {selector. select (); Set <SelectionKey> readyKeys = selector. selectedKeys (); Iterator <SelectionKey> iterator = readyKeys. iterator (); while (iterator. hasNext () {SelectionKey key = iterator. next (); iterator. remove (); if (key. isAcceptable () {System. out. println ("accept"); ByteBuffer byteBuffer = ByteBuffer. allocate (512); ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key. channel (); SocketChannel socketChannel = serverSocketChannel. accept (); socketChannel. configureBlocking (false); int readKeys = socketChannel. read (byteBuffer); if (readKeys> 0) {byteBuffer. flip (); System. out. println (new String (byteBuffer. array (), 0, readKeys);} socketChannel. write (ByteBuffer. wrap ("received ". getBytes ();} else if (key. isReadable () {System. out. println ("read");} else if (key. isWritable () {System. out. println ("write ");}}}}}