Echo Client via SocketChannel - Java Network

Java examples for Network:Socket Channel

Description

Echo Client via SocketChannel

Demo Code

import java.io.BufferedReader;
import java.io.EOFException;
import java.io.IOException;
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 {

  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();
  }//ww  w .  j  a va 2s .  co  m

  @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);

    System.out.println("Client read " + new String(receivedData).trim() + " at " + new Date());
  }

  private SocketChannel createSocketChannel() throws IOException {
    SocketChannel client = SocketChannel.open(new InetSocketAddress(mHostname, mPort));
    client.configureBlocking(false);
    return client;
  }

  public static void main(String[] args) throws Exception {
    String host = "192.168.0.3";

    NioEchoClient client = new NioEchoClient(host, PORT_NUMBER);
    Thread t = new Thread(client);
    t.start();
    t.join();
  }
}

Related Tutorials