Search code examples
javasocketstcpserversocket

Is it better to open different ports or one port with identifiers (or else)?


I'm coding a system in which there are three different java applications that interact with eachother via TCP-IP. Two of these apps connect with the other one, called Directory, through a ServerSocket.
One of the apps connects with it only to log in and be added to a list, while the other app connects with it only to ask for the list or to send a message.
These connections are all being done via the same port in the Directory's ServerSocket, the apps that connect with the Directory send a String through the socket with a sort of task-identifier slapped on the front, which the Directory then processes to know what it has to do.
Is this approach of reading identifier Strings ok? Is it efficient, maintainable, or should it be done in another way? e.g. having ServerSockets with different ports for different types of clients, or different ports for different funcionalities. The funcionalities mentioned are the only ones for the time being, but more may be added so I would like to know if this is a viable implementation.

public class Directory {
    private ServerSocket server;
    public Directory() {
        super();
    }

    public void openServer(int port) throws IOException {
        new Thread() {
            public void run() {
                try {
                    server = new ServerSocket(port);
                    while (true) {
                        Socket socket = server.accept();
                        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
                        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                        String identifier = in.readLine();
                        if (identifier.equalsIgnoreCase("Connect")) {
                            connect(); // stub
                        } else if (identifier.equalsIgnoreCase("NeedList")) {
                            giveList(list); // stub
                        } else if (identifier.equalsIgnoreCase("SendMessage")) {
                            sendMessage(); // stub
                        }
                    }
                } catch (IOException e) {
                    // interrupted
                }
            }
        }.start();
    }
}

Solution

  • If all apps use the same protocol, which basically just means as long as all apps use the same packet structure, you´re fine with going with one port. Another pro using one port is that it´s less coinfiguration since, let´s say you have a firewall, you only have to open this one port and if someone tries to connect within a restricted network, the same applies.

    If the apps use different protocols you´d be better off using three ports.