SocketChannel Creation

In this chapter you will learn:

  1. Create SocketChannel from IP address

Create SocketChannel from IP address

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.channels.SocketChannel;
//j a  v a 2  s.  c  o  m
public class MainClass {

  public static void main(String[] args) throws Exception {
    int port = 1919;

    SocketAddress address = new InetSocketAddress("127.0.0.1", port);
    SocketChannel client = SocketChannel.open(address);
    ByteBuffer buffer = ByteBuffer.allocate(4);
    IntBuffer view = buffer.asIntBuffer();

    for (int expected = 0;; expected++) {
      client.read(buffer);
      int actual = view.get();
      buffer.clear();
      view.rewind();

      if (actual != expected) {
        System.err.println("Expected " + expected + "; was " + actual);
        break;
      }
      System.out.println(actual);
    }
  }
}

Next chapter...

What you will learn in the next chapter:

  1. Reading from a SocketChannel
  2. Writing to a SocketChannel
Home » Java Tutorial » Socket

Socket

    Socket
    Socket creation
    Socket read
    HTTP client
    SMTP Client
    Cipher Socket
    Socket connection and thread

ServerSocket

    ServerSocket
    ServerSocket connection
    File server and client
    Thread based Server
    Time server
    SocketServer based zip server
    ServerSocketChannel
    Channel selector

SocketChannel

    SocketChannel Creation
    Read and write with SocketChannel
    SocketChannel based HTTP client
    SocketChannel Asynchronous

ServerSocketChannel

    ServerSocketChannel
    Channel selector

SSL

    SSL Client Socket
    SSL Server Socket

UDP

    DatagramSocket
    DatagramChannel
    Multicast Group

Cookie

    Cookies