Connection reset in sockets

1.2k Views Asked by At

I have a game like blackjack that I have a server and players. When I execute the server and the players in the same computer it works perfect. But when I execute the players in one pc and the server in another pc it works so rare. After some writebytes from server and some readLines from users it gives me "Java.net.SocketException: Connection reset".

Why is this happening?

            Socket registre = null;

            try{
                registre = new Socket(IP,port);
            }
            catch(java.net.ConnectException e){
                System.out.println("Servidor de partida incorrecte.");
                break;
            }
            catch(java.net.UnknownHostException e){
                System.out.println("Servidor de partida incorrecte.");
                break;
            }
            catch(java.net.SocketException e){
                System.out.println("Servidor de partida incorrecte.");
                break;
            }

            DataOutputStream sendToServer = new DataOutputStream(registre.getOutputStream());
            BufferedReader receiveFromServer = new BufferedReader(new InputStreamReader(registre.getInputStream())); 

            numCartes = 2;

            sendToServer.writeBytes("JUG"+"/"+portJug+ '\n');

            boolean llistaJugadors = false;

            servidorJoc = receiveFromServer.readLine().trim();
            System.out.println(servidorJoc);
            System.out.println("----------------------------------");

            while(!llistaJugadors){

                servidorJoc = receiveFromServer.readLine().trim();

                if (servidorJoc.equalsIgnoreCase("exit")){
                    llistaJugadors=true;
                }
                else{
                    System.out.println(servidorJoc);
                }
            }
            System.out.println("----------------------------------");

            boolean jocAcabat= false;               
            jugant = true;
            boolean canviant = false;
            String torn=null;
            boolean unCanviEfectuat=false;

            torn = receiveFromServer.readLine().trim(); 
            System.out.println(torn);

            String[] jug = torn.split("-");
            jugador = jug[1];
            jug = torn.split(":");
            float puntuacio = Float.parseFloat(jug[1]);

            if (puntuacio>=7.5){
                jugant=false;
            }

            while (!jocAcabat){

                if (canviant==false && jugant){
                    torn = receiveFromServer.readLine().trim();
                    System.out.println(torn);

                    if (llegirMes==1){
                        String[] infor = torn.split(":");

                        float passat = Float.parseFloat(infor[1]);

                        if (passat>=7.5){
                            jugant=false;
                            System.out.println("T'has passat amb puntuacio: "+passat);
                        }
                    }
                }

                if (llegirMes==1){
                    torn = receiveFromServer.readLine().trim();
                    System.out.println(torn);
                    llegirMes=0;
                    canviant=false;
                }


                String[] data = torn.split(":");

                if(data[0].trim().equalsIgnoreCase("torn") && jugant){

                    ImprimirMenu2();

                    fet=false;
                    int conf=0;

                    while (!fet){
                        try{
                            conf = Integer.parseInt(teclat.readLine());
                            if(conf<4 && conf>0){
                                fet=true;
                            }

                        }
                        catch(NumberFormatException e){
                            System.out.println("Intrudueix un enter entre 1-3");
                        }

                    }

                    switch (conf){

                    case 1:
                        canviant = false;
                        sendToServer.writeBytes("CARTA+" + "\n");
                        receiveFromServer = new BufferedReader(new InputStreamReader(registre.getInputStream())); 
                       torn = receiveFromServer.readLine().trim();  <----CRASH
                        System.out.println(torn);
                        String[] puntuacion = torn.split(":");
                        float punt = Float.parseFloat(puntuacion[1]);
                        if (punt>=7.5){
                            jugant=false;
                        }
                        unCanviEfectuat=false;
                        numCartes++;
                        break;
                    case 2:
                        canviant = false;
                        sendToServer.writeBytes("TREE" + "\n");
                        receiveFromServer = new BufferedReader(new InputStreamReader(registre.getInputStream()));  
                        torn = receiveFromServer.readLine().trim();     <----CRASH
                        System.out.println(torn);
                        jugant = false;
                        unCanviEfectuat=false;
                        break;

                    case 3:

                        if (unCanviEfectuat){
                            System.out.println("Ja has fet un canvi aquest torn, no pots fins el seguent.");
                            break;
                        }
                        else{
                            canviant = true;
                            System.out.println("Introdueix la ip del jugador: ");
                            llegit = false;
                            String ip = teclat.readLine();
                            int portJugador = 0;
                            System.out.println("Introdueix el port: ");

                            while(!llegit){

                                try{
                                    portJugador = Integer.parseInt(teclat.readLine());
                                    llegit=true;
                                }
                                catch(NumberFormatException e){
                                    System.out.println("Has introduit un valor incorrecte.");
                                }
                            }

                            Socket conectarjugador = null;

                            try{
                                conectarjugador = new Socket(ip,portJugador);
                            }

                            catch(java.net.ConnectException e){
                                System.out.println("Jugador incorrecte");
                                break;
                            }

                            catch(java.net.UnknownHostException e){
                                System.out.println("Jugador incorrecte");
                                break;
                            }

                            catch(java.net.SocketException e){
                                System.out.println("Servidor de partida incorrecte.");
                                break;
                            }

                            BufferedReader receiveFromJugador = new BufferedReader(new InputStreamReader(conectarjugador.getInputStream())); 

                            String info = receiveFromJugador.readLine().trim();

                            if (info.equalsIgnoreCase("estic plantat!")){
                                System.out.println("El jugador es troba plantat. No pot canviar Cartes.");
                                break;
                            }
                            else{

                                if (info.equalsIgnoreCase("deny.")){
                                    System.out.println("El jugador no vol fer el canvi.");
                                    break;
                                }

                                else {
                                    System.out.println("El jugador ha acceptat el canvi, procedim a efectuar els canvis.");

                                    info = receiveFromJugador.readLine().trim();

                                    String[] informacio = info.split(":");
                                    int cartaCanviarJug2 = Integer.parseInt(informacio[0]);
                                    String jugadorCanvi = informacio[1];

                                    unCanviEfectuat=true;

                                    min =0;
                                    max = numCartes-1;
                                    rand = new Random();
                                    int cartaCanviar = rand.nextInt((max-min)+1)+min;

                                    sendToServer.writeBytes("CHANGE:"+jugador+":"+cartaCanviar+":"+jugadorCanvi+":"+cartaCanviarJug2+ "\n");

                                    info = receiveFromServer.readLine().trim();

                                    informacio = info.split(":");
                                    float passat = Float.parseFloat(informacio[1]);

                                    if (passat>=7.5){
                                        jugant=false;
                                        System.out.println(info);
                                        System.out.println("T'has passat amb puntuacio: "+passat);
                                    }
                                    else{
                                        System.out.println(info);
                                    }

                                }
                            }
                        }
                        break;
                    }
                }

                else {

                    jugant=false;
                    boolean noAcabat=true;
                    while (noAcabat){

                        try{
                            torn = receiveFromServer.readLine().trim();     
                        }
                        catch(java.net.SocketException e) {
                            return;
                        }
                        System.out.println(torn);
                        data = torn.split(":");

                        if (data[0].equalsIgnoreCase("Resultat")){
                            torn = receiveFromServer.readLine().trim();     
                            if (torn.equalsIgnoreCase("has guanyat")){
                                System.out.println("      @@ "+ torn + " @@");
                            }
                            else{
                                System.err.println("      @@ "+ torn + " @@");
                            }

                            return;

                        }
                    }
                }
            }

            break;
        case 3:
            System.out.println("Has desconectat.");
            return;

        default:
            break;
        }

    }

    return;
}
1

There are 1 best solutions below

4
On

You aren't checking a single readLine() result for null. As a result, you have no hope of detecting a peer disconnect in the normal way. Every time you call readLine(), the first thing you must do is check for null, and if so close the socket and bail out.

Your exception handling is also poor. Code that depends on the success of code in a try block should be inside the same try block.