SocketDemo.java

Socket class documentation.

Java tutorial: All About Sockets.

Wikipedia article: Network Socket


// Demonstrate Sockets.

import java.net.*;
import java.io.*;

class SocketDemo {
  public static void main(String[] args) {
    int ch;
    Socket socket = null;
    int port = 43;

    try {
      // Create a socket connected to whois.internic.net, port 43.
      socket = new Socket("whois.internic.net", port);

      // Obtain input and output streams.
      InputStream in = socket.getInputStream();
      OutputStream out = socket.getOutputStream();

      // Construct a request string.
      String str = (args.length == 0 ? "udayton.edu" :
                                      args[0]) + "\n";
      // Convert to bytes.
      byte[] buf = str.getBytes();

      // Send request.
      out.write(buf);

      // Read and display response.
      while ((ch = in.read()) != -1) {
        System.out.print((char) ch);
      }
    } catch(IOException exc) {
      System.out.println(exc);
    } finally {
      try {
        if(socket != null) socket.close();
      } catch(IOException exc) {
        System.out.println("Error closing socket: " + exc);
      }
    }
  }
}


Results


Whois Server Version 2.0

Domain names in the .com and .net domains can now be registered
with many different competing registrars. Go to http://www.internic.net
for detailed information.

   Domain Name: MCGRAW-HILL.COM
   Registrar: CSC CORPORATE DOMAINS, INC.
   Whois Server: whois.corporatedomains.com
   Referral URL: http://www.cscglobal.com
   Name Server: CORP-55W-NS1.MCGRAW-HILL.COM
   Name Server: CORP-HTS-NS1.MCGRAW-HILL.COM
   Name Server: CORP-UKC-NS1.MCGRAW-HILL.COM
   Status: clientTransferProhibited
   Updated Date: 09-dec-2011
   Creation Date: 07-may-1994
   Expiration Date: 08-may-2013

...

Reference

Herbert Schildt and Dale Skrien, Java Programming, A Comprehensive Introduction,
McGraw-Hill, 2013. ISBN 978-0-07-802207-4. p 989-993.


Maintained by John Loomis, updated Wed Nov 14 13:10:38 2012