通过SocketChannel回显客户端
import java.io.BufferedReader; import java.io.EOFException; import java.io.IOException;/**from n o w j a v a . c o m**/ import java.io.InputStreamReader; 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.Date; import java.util.Iterator; class NioEchoClient implements Runnable { // 来自 nowjava.com private static final int PORT_NUMBER = 9000; private static final long TIME_OUT = 3000; private static final byte LF = 0x0A; private static final byte CR = 0x0D; private String mHostname; private int mPort; private Selector mSelector; private final ByteBuffer mReadBuffer = ByteBuffer.allocate(8192); public NioEchoClient(String host, int portNumber) throws IOException { this.mHostname = host; this.mPort = portNumber; this.mSelector = Selector.open(); } @Override public void run() { SocketChannel client = null; try (BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in))) { client = createSocketChannel(); if (!client.isConnected()) { client.finishConnect(); } System.out.println("input data to send to the server."); String line = null; while ((line = keyboard.readLine()) != null) { if ("quit".equals(line)) break; client.register(mSelector, SelectionKey.OP_WRITE); while (mSelector.select(TIME_OUT) != 0) { Iterator<SelectionKey> selectedKeys = mSelector.selectedKeys().iterator(); while (selectedKeys.hasNext()) { SelectionKey key = selectedKeys.next(); selectedKeys.remove(); if (!key.isValid()) continue; if (key.isReadable()) { readData(key); } else if (key.isWritable()) { writeData(key, line); } } } } } catch (EOFException e) { } catch (IOException e) { e.printStackTrace(); } finally { try { client.close(); } catch (IOException e) { e.printStackTrace(); } } System.out.println("client exits"); } private void writeData(SelectionKey key, String line) throws IOException { SocketChannel client = (SocketChannel) key.channel(); mReadBuffer.clear(); mReadBuffer.put(line.getBytes()); mReadBuffer.put(LF); mReadBuffer.flip(); client.write(mReadBuffer); System.out.println("Client send " + line + " at " + new Date()); client.keyFor(mSelector).interestOps(SelectionKey.OP_READ); } private void readData(SelectionKey key) throws IOException { SocketChannel client = (SocketChannel) key.channel(); mReadBuffer.clear(); int numRead; int totalRead = 0; while ((numRead = client.read(mReadBuffer)) > 0) { totalRead = numRead; } if (numRead < 0) { client.close(); key.cancel(); throw new EOFException(); } mReadBuffer.flip(); byte[] receivedData = new byte[totalRead]; System.arraycopy(mReadBuffer.array(), 0, receivedData, 0, totalRead);