0
public static void main(String[] args) {

    ServerSocket server_socket = null;
    ServerSocket server_socket2 = null;
    Socket command_socket = null;
    Socket file_socket = null;

        try {
            server_socket = new ServerSocket(1234);
            server_socket.setReuseAddress(true);
        while (true) {
            command_socket = server_socket.accept();
            System.out.println("Connection established with a client with the address: "
                    + command_socket.getRemoteSocketAddress());
            ServerThread st = new ServerThread(command_socket);
            new Thread(st).run();

            
                server_socket2 = new ServerSocket(6942);
                server_socket2.setReuseAddress(true);
                file_socket = server_socket2.accept();
                new Thread(st).run();
                System.out.println("Connection established with a client with the address: "
                        + file_socket.getRemoteSocketAddress()); ...

I have this code, I want to create a new socket to transfer data and use the first socket as a command socket. However, My second socket does not work. It does not print the second connection. How can I make it possible to use 2 sockets? Thanks...

user207421
  • 305,947
  • 44
  • 307
  • 483
  • 3
    Did you connect to the second socket? – Kayaman Mar 15 '21 at 20:48
  • Calling `setReuseAddress()` *after* you've bound the socket is futile. Create the `ServerSocket` unbound, with the no-args constructor, then call `setReuseAddress()`, then bind it. – user207421 Mar 16 '21 at 00:14
  • However your scheme is unreliable. How can you ensure that any given client will perform two connections without getting interleaved with connections from other clients? – user207421 Mar 16 '21 at 00:14
  • why do you start the same ServerThread twice? – user253751 Mar 16 '21 at 12:54
  • 1
    Actually he isn't starting any threads at all. Just calling `run()` inline. This will be why his code doesn't work. Should be calling `start()`, not `run()`. But it still doesn't make sense. @user253751 – user207421 Mar 17 '21 at 01:29

0 Answers0