Home > Software engineering >  JAVA SOCKETS: Connection timed out: connect
JAVA SOCKETS: Connection timed out: connect

Time:07-11

Socket server and socket client are not connecting, I'm using port 8080 in both aplications In the server:

public ServidorWeb(String nombre) {
        this.nombre=nombre;
        puerto=8080;
    }

    public void iniciar() throws IOException {
        ServerSocket serverSocket = new ServerSocket(puerto);
        while (true){
            Socket cliente = serverSocket.accept();
            System.out.println("I'm listening");
            InputStream entrada = cliente.getInputStream();
            DataInputStream entradaCliente = new DataInputStream(entrada);
            OutputStream salida = cliente.getOutputStream();
            DataOutputStream salidaCliente = new DataOutputStream(salida);

            String pedido = entradaCliente.readUTF();
            System.out.println(pedido);
            String respuesta=obtenerRespuesta(pedido);
            salidaCliente.writeUTF(respuesta);
            cliente.close();
        }
    }

In client

int puerto=8080;
 try {
                    Socket socket = new Socket(ip,puerto);
                    InputStream streamEntrada = socket.getInputStream();
                    DataInputStream entrada = new DataInputStream(streamEntrada);
                    OutputStream streamSalida = socket.getOutputStream();
                    DataOutputStream salida = new DataOutputStream(streamSalida);
                    
                    salida.writeUTF("GET;" recursoPedido);
                    String respuesta=entrada.readUTF();
                    
                    System.out.println(respuesta);
                    return respuesta;
                } catch (IOException e) {
                    e.printStackTrace();
                }

but when trying to connect I get Connection timed out: connect. What am I doing wrong?

CodePudding user response:

The code is okay but the IP I was sending in the Client code was wrong. I changed it to 127.0.0.1 and worked.

CodePudding user response:

its cause for your entered IP.
you have two choices:

  1. run client and server both on same pc:
    for do this just need to set IP "127.0.0.1" or "localhost"

  2. run client and server on different pc:
    and it divide to two state again:

    1. your both pc are connected to same router: in this state just you need to set IP with your server default gateway like "192.168.1.3"

    2. your both pc are not connected to same router: in this state you should first forward your 8080 port in your server router and then set IP with your server public IP.

  • Related