Java API Tutorial - Java Socket.getChannel()








Syntax

Socket.getChannel() has the following syntax.

public SocketChannel getChannel()

Example

In the following code shows how to use Socket.getChannel() method.

/*from  w w w.j  a va 2s. co  m*/

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.channels.SocketChannel;

public class Main {
  public static void main(String args[]) throws Exception {
    Socket s = new Socket("internic.net", 43);
    InputStream in = s.getInputStream();
    OutputStream out = s.getOutputStream();
    String str = "asdfasdfasdf\n";
    byte buf[] = str.getBytes();
    out.write(buf);
    int c;
    while ((c = in.read()) != -1) {
      System.out.print((char) c);
    }
    
    SocketChannel socketChannel = s.getChannel();
    System.out.println(socketChannel.getLocalAddress());

    
    s.close();
  }
}