简体   繁体   中英

JAVA SOCKETS: Connection timed out: connect

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?

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM