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 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
|
public class NioClient extends AbstractNio { private Selector selector; private static final int BUFFER_SIZE = 2048; private ByteBuffer sendBuffer = ByteBuffer.allocate(BUFFER_SIZE); private ByteBuffer receiveBuffer = ByteBuffer.allocate(BUFFER_SIZE);
void connectedServer(final String ip, final int port) throws IOException { SocketChannel socketChannel = SocketChannel.open(); socketChannel.configureBlocking(false); socketChannel.connect(new InetSocketAddress(ip, port)); selector = Selector.open(); socketChannel.register(selector, SelectionKey.OP_CONNECT); System.out.println("client connect to server!"); }
@Override void handlerKey(SelectionKey key) throws IOException { SocketChannel client; int count; if (key.isConnectable()) { client = (SocketChannel) key.channel(); if (client.isConnectionPending()) { client.finishConnect(); } client.configureBlocking(false); client.register(selector, SelectionKey.OP_WRITE); } else if (key.isReadable()) { client = (SocketChannel) key.channel(); receiveBuffer.clear(); count = client.read(receiveBuffer); if (count > 0) { receiveBuffer.flip(); String msg = new String(receiveBuffer.array(), 0, receiveBuffer.limit()); System.out.println("client received msg:" + msg); client.register(selector, SelectionKey.OP_WRITE); } } else if (key.isWritable()) { sendBuffer.clear(); client = (SocketChannel) key.channel(); String msg = "msg from client"; sendBuffer.put(msg.getBytes()); sendBuffer.flip(); client.write(sendBuffer); client.register(selector, SelectionKey.OP_READ); } }
public static void main(String[] args) throws IOException { NioClient client = new NioClient(); client.connectedServer("127.0.0.1", 9997); client.listen(client.getSelector()); }
public Selector getSelector() { return selector; }
public void setSelector(Selector selector) { this.selector = selector; } }
|