Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Server Listening on Multiple Ports [Java]

I am trying to figure out how to create a java program that can listen to multiple ports and perform different actions depending on which port the client speaks to.

I've seen and understand the basic client-server program: http://systembash.com/content/a-simple-java-tcp-server-and-tcp-client/

Just to reiterate, I want to create this same relationship, but instead of the server only listening on one port and performing one action when it receives input, I want it to listen on multiple ports and depending which port the client connects and sends data to, perform a different action.

I'm hoping to make each port accept a GET and PUT command in the future, but for now I'm just trying to figure out how to set up the basic structure of the server which will be able to listen to multiple ports. I've tried googling, but I can't seem to find much, so any help is appreciated.

Thanks in advance. -Anthony

like image 606
AnthonyJK Avatar asked Jan 20 '23 11:01

AnthonyJK


1 Answers

The tutorial you've mentioned is very basic. You cannot write any reasonable server without using threads. In order to have two server sockets, you must spawn a new thread for each port, like this (pseudocode):

new Thread() {
    public void run() {
        ServerSocket server = new ServerSocket(6788);
        while(true) {
            Socket client1 = server.accept();
            //handle client1
        }
    }.start();

and (notice the different port):

new Thread() {
    public void run() {
        ServerSocket server = new ServerSocket(6789);
        while(true) {
            Socket client1 = server.accept();
            //handle client2
        }
    }.start();

Having client1 and client2 sockets you can handle them separately. Also, handling client connection should be done in a different thread so that you can serve multiple clients. Of course this code introduces a lot of duplication, but consider this as a starting point.

To wrap things up - if your goal is to implement HTTP GET and PUT, use servlet and get away from all this hustle.

like image 70
Tomasz Nurkiewicz Avatar answered Feb 06 '23 03:02

Tomasz Nurkiewicz