TCP/IP Client Socket in Advanced Java

TCP/IP Client Socket in Java:

In Java, TCP/IP Client Socket used to implement reliable, bidirectional, persistent, point-to-point, stream-based connections between hosts on the Internet. A socket can be used to connect Java’s I/O system to other programs that may reside either on the local machine or on any other machine on the Internet.

There are two kinds of TCP/IP Client Sockets in Java. One is for servers, and the other is for clients. The ServerSocket class designed to be a “listener,” which waits for clients to connect before doing anything. Thus, ServerSocket is for servers. The Socket class is for clients. It designed to connect to server sockets and initiate protocol exchanges.

Constructor to Create TCP/IP Client Socket:

Socket(String hostName, int port) throws UnknownHostException, IOException: Creates a socket connected to the named host and port.

Socket(InetAddress ipAddress, int port) throws IOException: Creates a socket using a preexisting InetAddress object and a port.

Instance Methods of TCP/IP Client Socket:

InetAddress getInetAddress(): Returns the InetAddress associated with the Socket object. It returns null if the socket is not connected.

int getPort(): It returns the remote port to which the invoking Socket object is connected. It returns 0 if the socket is not connected.

int getLocalPort(): It returns the local port to which the invoking Socket object is bound. It returns –1 if the socket is not bound.

I/O Stream of TCP/IP Client Socket:

InputStream getInputStream( ) throws IOException: Returns the InputStream associated with the invoking socket.
OutputStream getOutputStream( ) throws IOException: Returns the OutputStream associated with the invoking socket.

Demontrate TCP/IP Client Socket Program:

class Whois 
public static void main(String args[]) throws Exception 
  int c;
 Socket s = new Socket("", 43);
 InputStream in = s.getInputStream();
 OutputStream out = s.getOutputStream();
 String str = (args.length == 0 ? "" : args[0]) + "\n";
 byte buf[] = str.getBytes();
 while ((c = != -1) {
 System.out.print((char) c);