Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium


Socket connection

Posted on 2003-03-21
Medium Priority
Last Modified: 2010-03-31
I have to write a program in which the parent thread should listen in one particular port and the child thread should listen in different port.Please let me know whether it is possible or not. if possible, pl give some pointers to implement
Question by:tamilselvi

Expert Comment

ID: 8185601
create a main program which handles 2 threads.
the main thread is handling 2 child threads, and thse child threads listne on 2 different ports
LVL 30

Accepted Solution

Mayank S earned 90 total points
ID: 8193398
>> the parent thread should listen in one particular port

Let the main thread listen to a port using ServerSocket.

>> the child thread should listen in different port

Spawn a new thread from the main () thread and let it listen to a different port, again using ServerSocket.

class MyApp
  public static void main ( String args[] )
    throws Exception
    new ChildThread () ;
    ServerSocket ss = new ServerSocket ( 1786 ) ; // listens to 1786

  } // end of main ()

} // class definition over

class ChildThread extends Thread
  ServerSocket ss ;

  ChildThread ()
    start () ;

  } // end of constructor ()

  public void run ()
      ss = new ServerSocket ( 2025 ) ; // listens to 2025

    } // end of try block

    catch ( Exception e )

    } // end of catch block

  } // end of run ()

} // class definition over

The accept () method of ServerSocket returns a Socket object after accepting a connection from a client at the specified port no. And don't forget to put a call to the join () method in main (), in case there are chances of the main thread finishing execution before the child thread.


Featured Post

Receive 1:1 tech help

Solve your biggest tech problems alongside global tech experts with 1:1 help.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
This video teaches viewers about errors in exception handling.
Suggested Courses
Course of the Month14 days, 6 hours left to enroll

581 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question