Thursday, 8 August 2013

How to Open a Socket on Server - In Java Programming


  Socket MyClient;

   MyClient = new Socket("Machine name", PortNumber); 

 

Machine name is the machine you are trying to open a connection to(ex: ip address or workstation name), and PortNumber is the port (a number) on which the server you are trying to connect to is running.

 

When selecting a port number, you should note that port numbers between 0 and 1,023 are reserved for privileged users (that is, super user or root)

 

These port numbers are reserved for standard services, such as email, FTP, and HTTP.

 

When selecting a port number for your server, select one that is greater than 1,023! 


 

With exception handling, the code look like following:


  Socket MyClient;

  try {

       MyClient = new Socket("Machine name", PortNumber);

   }

   catch (IOException e) {

         System.out.println(e);

ServerSocketMyService;
   }


  try {

       MyServerice = new ServerSocket(PortNumber);

   }

   catch (IOException e) {

       System.out.println(e);

 

   }
 

When implementing a server you also need to create a socket object from the ServerSocket in order to listen for and accept connections from clients.


  Socket clientSocket = null;

  try {

        serviceSocket = MyService.accept();

    }

  catch (IOException e) {

        System.out.println(e);

  

0 comments:

Post a Comment

Products :