Listening on a server on multiple ports [Java]

I'm trying to figure out how to create a java program that can listen on several ports and perform different actions depending on which port the client is talking to.

I saw and understood the basic client-server program: http://systembash.com/content/a-simple-java-tcp-server-and-tcp-client/

To repeat, I want to create the same connection, but instead of letting the server only listen on one port and perform one action upon input, I want it to listen on several ports and depend on which port the client connects to and send data , performs another action.

I hope that each port will accept a GET and PUT command in the future, but for now I’m just trying to figure out how to set up a basic server structure that can listen on multiple ports. I tried searching on the internet, but I can not find much, so any help would be appreciated.

Thanks in advance. -Anthony

+4
source share
3 answers

A socket can only be opened for a specific port, so you need several server sockets (for example, 1 socket per port). I think you also need one thread per socket so that network activity on one socket does not interfere with activity on the other.

Are you implementing the server as an academic exercise? If not, I really really really really really highly recommend using an existing server like Tomcat .

+2
source

The tutorial you mentioned is very simple. You cannot write any reasonable server without using threads. To have two server sockets, you must create a new thread for each port, for example this (pseudo-code):

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

and (pay attention to another port):

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

Having sockets client1 and client2 , you can process them separately. In addition, client connection processing must 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 a starting point.

To wrap everything - if your goal is to implement HTTP GET and PUT, use a servlet and avoid all this fuss.

+6
source

Of course, you can open multiple server sockets.

You can also look at jboss netty, which will help you implement the protocols.

0
source

Source: https://habr.com/ru/post/1340075/


All Articles