Help with Socket in java

0

I hope you can help me, I am a little or very confused with Sockets in java, the exercise is the following ...

Create a server client application where the server "thinks a number" in an interval known and the client tries to guess it. The client sends to the server the possible number and to help to the client, the server can respond to the client any of the following answers:

 You guessed it

 Try above

 Try below

The client must guess in a minimum number of attempts. At the end of the server it will send you the number of attempts.

In my case I put 5 attempts ...

The server code is this ...

package socket3;
import java.net.*;
import java.io.*;
import java.util.Scanner;
import java.util.Random;
import java.security.SecureRandom;

/**
 *
 * @author Palomita
 */
public class Socket3 {
    public static void main(String[] args){

    /**
     * @param args the command line arguments
     */
        try{
            ServerSocket servidor=new ServerSocket(4500);
            Socket cliente=servidor.accept();
            long startTime = System.currentTimeMillis();
            System.out.println("Un cliente se conectó");


            DataInputStream in=new DataInputStream(cliente.getInputStream());
            DataOutputStream out=new DataOutputStream(cliente.getOutputStream());
            ObjectOutputStream resp=new ObjectOutputStream(cliente.getOutputStream());
            //resp.writeObject("Hora y fecha: "+hourdateFormat.format(date));

            BufferedReader b=new BufferedReader(new InputStreamReader(System.in));

            String menin=("");
            String menout=("");
            Random genera= new Random();
            int aleatorio = 1+genera.nextInt(10);

            for(int j=1;j<=5;j++){
                while(j<=5){
                    resp.writeObject("ADIVINA EL NUMERO DEL 1 AL 10 EN 5 INTENTOS");
                    menin=in.readUTF();
                    int num=Integer.parseInt(menin);
                    for(int i=1;i<5;i++){
                        if(aleatorio==num){
                        System.out.println("Adivinaste en "+i+" intentos.");
                        cliente.close();
                        break;
                    }
                    else if(aleatorio>num){
                        System.out.println("Intenta Arriba, te quedan "+i+" intentos.");
                    }
                    else if(aleatorio<num){
                        System.out.println("Intenta Abajo, te quedan "+i+" intentos");
                    }
                }
                cliente.close();
                break;
                }
            }
        }catch(Exception e){
           e.printStackTrace();
        }
    }
}

And the Client's code is this ...

import java.net.*;
import java.io.*;
import java.util.Scanner;

/**
 *
 * @author Palomita
 */
public class Cliente {
    public static void main(String[] argumentos) {
        try{
            Socket cliente=new Socket("localhost",4500);
            DataInputStream in=new DataInputStream(cliente.getInputStream());
            DataOutputStream out=new DataOutputStream(cliente.getOutputStream());

            BufferedReader b=new BufferedReader(new InputStreamReader(System.in));

            String menin=("");
            String menout=("");

            for(int j=1;j<=5;j++){
                while(j<=5){
                    ObjectInputStream entrada=new ObjectInputStream(cliente.getInputStream());
                    String mensaje2=(String) entrada.readObject();
                    System.out.println(mensaje2);
                    menout=b.readLine();
                    out.writeUTF(menout);
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

In the end, this error marks me in the Server code ...

Un cliente se conectó

Intenta Abajo, te quedan 1 intentos

Intenta Abajo, te quedan 2 intentos

Intenta Abajo, te quedan 3 intentos

Intenta Abajo, te quedan 4 intentos

java.net.SocketException: Socket closed
    at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:118)
    at java.net.SocketOutputStream.write(SocketOutputStream.java:155)
    at java.io.ObjectOutputStream$BlockDataOutputStream.drain(ObjectOutputStream.java:1877)
    at java.io.ObjectOutputStream$BlockDataOutputStream.setBlockDataMode(ObjectOutputStream.java:1786)
    at java.io.ObjectOutputStream.writeNonProxyDesc(ObjectOutputStream.java:1286)
    at java.io.ObjectOutputStream.writeClassDesc(ObjectOutputStream.java:1231)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1427)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
    at java.io.ObjectOutputStream.writeFatalException(ObjectOutputStream.java:1577)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:351)
    at socket3.Socket3.main(Socket3.java:39)
BUILD SUCCESSFUL (total time: 17 seconds)

And this error in the Client code ...

java.io.EOFException
    at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2681)
    at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:3156)
    at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:862)
    at java.io.ObjectInputStream.<init>(ObjectInputStream.java:358)
    at Cliente.main(Cliente.java:23)
BUILD SUCCESSFUL (total time: 4 seconds)

I hope you can help me: (

    
asked by Paloma Martínez 03.11.2018 в 21:42
source

1 answer

1
  • A problem arises when the socket of the customer in the class Socket3 within the loops ( 2 of which result potentially redundant ), said socket must be closed outside of the iteration of the first for .
  • Now, taking and commenting on the code     What do you provide:

    Socket3 Class:

    try {
      //...
      //...
    
      for(int j=1;j<=5;j++){
        //while(j<=5){
          resp.writeObject("ADIVINA EL NUMERO DEL 1 AL 10 EN 5 INTENTOS");
          menin=in.readUTF();
          int num=Integer.parseInt(menin);
          //for(int i=1;i<5;i++){
              if(aleatorio==num){
                System.out.println("Adivinaste en "+j+" intentos.");
                //cliente.close();
                break;
              } else if(aleatorio>num){
                System.out.println("Intenta Arriba, te quedan "+(5-j)+" intentos.");
              } else if(aleatorio<num){
                System.out.println("Intenta Abajo, te quedan "+(5-j)+" intentos");
              }
          //} fin for
          //cliente.close();
          //break;
        //} fin while
      }
      cliente.close();
    } catch(Exception e){
      e.printStackTrace();
    }
    
  • A problem arises when you try, for each iteration, to create a new object ObjectInputStream , you only need one, so entrada must be instantiated outside of the cycle for .
  • Likewise, taking the code and modifying:

    Client Class:

    //...
    
    ObjectInputStream entrada=new ObjectInputStream(cliente.getInputStream());
    for(int j=1;j<=5;j++){
      //while(j<=5){
        //ObjectInputStream entrada=new ObjectInputStream(cliente.getInputStream());
        String mensaje2=(String) entrada.readObject();
        System.out.println(mensaje2);
        menout=b.readLine();
        out.writeUTF(menout);
      //}
    }
    
      //...
    

    After the previous debugging:

        
    answered by 04.11.2018 в 00:43