Multithreaded Server in Java - connection timeout exception while connecting from other computer

140 views Asked by At

I have a problem with my application. If I run server and clients on the same computer it works fine. No errors. But if I run server on one PC and I try to connect form other computers I get "timeout exception" or If I manage to connect I will get errors while sending data.

Server code (not all):

// server loop - listening for connections
public void runServer()
    {
        try {

            ServerSocket serverSocket = new ServerSocket(port, 10);            
            System.out.println("Server up.");
            while (true) 
            {
                System.out.println("waiting for new connection...");
                Socket socket = serverSocket.accept();
                System.out.println("Someone connected");
                Thread t = new Thread (new ServerThread(socket));
                t.start();
                System.out.println("new thread");
            }

        } catch (IOException ex) {
            Logger.getLogger(KsiegarniaServer.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("Server error");
        }



// this is thread that is opened when new client connects
private class ServerThread implements Runnable 
    {       
        Socket socket;
        ObjectInputStream in;
        ObjectOutputStream out;
        String playerLogin;
        int playerID;

        public ServerThread(Socket s) {
            this.socket = s;            
        }
        public void run() {

            try {
                Msg m;
                in = new ObjectInputStream(socket.getInputStream());
                out = new ObjectOutputStream(socket.getOutputStream());
                System.out.println("Streams are ready!");
                while ( (m = (Msg) in.readObject()).getHeader() != 0 ) 
                {   
                      respondToClient(m); // switch with cases that are running depending on message header

                }               


            } catch (IOException ex) {
                //Logger.getLogger(SpaceBattleGameServer.class.getName()).log(Level.SEVERE, null, ex);
                System.out.println("IOException - public void run()");
            } catch (ClassNotFoundException e) {
                System.out.println("ClassNotFoundException - public void run()");
            } finally {
        // other stuff
            }
0

There are 0 answers