-1

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;
}
eightShirt
  • 1,457
  • 2
  • 15
  • 29
user2911701
  • 69
  • 1
  • 10

1 Answers1

3

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.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • It's so rare, but when I execute my code in my house it dosn't work, but when I do this in the University internet it works. This can be a router problem? – user2911701 Nov 28 '14 at 10:45
  • No, it's a coding problem. You're sending to a connection that has already been closed by the peer, and the defects I mentioned are preventing you from detecting this disconnection properly, so you're detecting it via this exception. Fix your code. – user207421 Nov 28 '14 at 11:03
  • I know what u are saying, but I mean that i tryed to run it in my home (2 PC + 1 laptop) and it did not worked, conexion reset ERROR. But when i tryed it on the university (3 PCS), it worked as many times I runed it without any error. Why this happened? – user2911701 Nov 28 '14 at 14:57
  • It is pointless to enquire. Your code is invalid. Fix it along the lines we have discussed; re-test; report the results here; then we will discuss further. – user207421 Dec 01 '14 at 01:24