Writing a Blocking TCP Client with SocketChannel - Java Network

Java examples for Network:Socket Channel

Introduction

Create a selectable channel for a stream-oriented connecting socket.

Demo Code

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

public class Main {
  public static void main(String[] args) {
    ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
    ByteBuffer helloBuffer = ByteBuffer.wrap("Hello !".getBytes());
    Charset charset = Charset.defaultCharset();
    CharsetDecoder decoder = charset.newDecoder();
    try (SocketChannel socketChannel = SocketChannel.open()) {
      if (socketChannel.isOpen()) {
        socketChannel.configureBlocking(true);
        socketChannel.setOption(StandardSocketOptions.SO_RCVBUF, 128 * 1024);
        socketChannel.setOption(StandardSocketOptions.SO_SNDBUF, 128 * 1024);
        socketChannel.setOption(StandardSocketOptions.SO_KEEPALIVE, true);
        socketChannel.setOption(StandardSocketOptions.SO_LINGER, 5);
        socketChannel.connect(new InetSocketAddress("127.0.0.1", 5555));
        if (socketChannel.isConnected()) {
          socketChannel.write(helloBuffer);
          while (socketChannel.read(buffer) != -1) {
            buffer.flip();//  w  w w.j  av a 2s .com
            CharBuffer charBuffer = decoder.decode(buffer);
            System.out.println(charBuffer.toString());
            if (buffer.hasRemaining()) {
              buffer.compact();
            } else {
              buffer.clear();
            }
            socketChannel.write(ByteBuffer.wrap("test".getBytes()));
          }
        } else {
          System.out.println("The connection cannot be established!");
        }
      } else {
        System.out.println("The socket channel cannot be opened!");
      }
    } catch (IOException ex) {
      System.err.println(ex);
    }
  }
}

Result


Related Tutorials