Skip to content
Advertisement

Java: Start a socket server class with the port as an argument

So i have a load balancer and when a server is full of clients i want to create a new multithread server programmatically by passing the server port as an argument.

This is how im trying to start a new server instance

int newport = 4001
SMTPserver server = new SMTPserver();
server.SMTPserver(port);

this is my server

public class SMTPserver {
    public static Socket connsock = null;
    public static int port;

//     SMTPserver(int port) {
//        this.port = port;
//    }

    public static void main(String args[]) throws IOException {

        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("Server is running on port " + port);

        while (true) {

            try {

                // accepting client socket
                connsock = serverSocket.accept();
                }
        }
    }
}

my question is how to start this server with the giver port argument? is this code correct?

Advertisement

Answer

You are passing 0 to the ServerSocket constructor, so it will choose an available port. You need to pass a non zero port number if you want to use a specific port.

You could do it like this:

public class SMTPserver {
    public Socket connsock = null;
    public int port;

    public SMTPserver(int port) {
        this.port = port;

        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("Server is running on port " + port);

        while (true) {

            try {

                // accepting client socket
                connsock = serverSocket.accept();
                }
        }
    }
}

Notice that I’m assigning the port parameter to the port field, and then passing it to the ServerSocket constructor.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement