Tutorials Point


  Java Basics Examples
  Java Tutorial
  Java Useful Resources
  Selected Reading

© 2011 TutorialsPoint.COM


  Home     References     Discussion Forums     About TP  

Java Examples - Connecting Socket


previous next AddThis Social Bookmark Button


Problem Description:

How to make a srever to allow the connection to the socket 6123?

Solution:

Following example shows how to make a srever to allow the connection to the socket 6123 by using server.accept() method of ServerSocket class andb sock.getInetAddress() method of Socket class.

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketDemo {
   public static void main(String[] args) {
      try {
         ServerSocket server = new ServerSocket(6123);
         while (true) {
            System.out.println("Listening");
            Socket sock = server.accept();
            InetAddress addr = sock.getInetAddress();
            System.out.println("Connection made to "
            + addr.getHostName()
            + " (" + addr.getHostAddress() + ")");
            pause(5000);
            sock.close();
         }
      }
	  catch (IOException e) {
         System.out.println("Exception detected: " + e);
      }
   }
   private static void pause(int ms) {
      try {
         Thread.sleep(ms);
      }
      catch (InterruptedException e) {
      }
   }
}

Result:

The above code sample will produce the following result.

Listening
Terminate batch job (Y/N)? n 
Connection made to 112.63.21.45


previous next Printer Friendly



  

Advertisement

Online Image Processing

Indian Baby Names