首页 > 解决方案 > 客户端/服务器套接字不适用于外部连接

问题描述

我用 java(client) 和 python3(server) 制作了一个服务器/客户端套接字,它在 localhost 上运行良好,但是当我尝试使用公共 IP 连接时,它无法建立 tcp/ip 连接。我打开了路由器的端口(65432)并将“端口转发”到分配给我的服务器机器的本地 IP(192.168.1.200),是静态的。我禁用了所有防火墙以测试它是否有效,但什么也没有。

这里有客户端代码:

    public class Service {

    public static void main(String[] args) {
        String hostname = "XX.XXX.XX.XXX"; //Here the public ip of my router
        int port = 65432;

        try (Socket socket = new Socket(hostname, port)) {

            // Obtenemos el canal de entrada
            DataInputStream entrada = new DataInputStream(socket.getInputStream());
            DataOutputStream dout = new DataOutputStream(socket.getOutputStream());
            dout.writeUTF("0x03");
            System.out.println("Send");

            byte string_entrada = entrada.readByte();
            System.out.println(string_entrada);

            entrada.close();
            dout.flush();
            dout.close();
            socket.close();

        } catch (UnknownHostException ex) {

            System.out.println("Server not found: " + ex.getMessage());

        } catch (IOException ex) {

            System.out.println("I/O error: " + ex.getMessage());
        }
    }
}

和服务器(Python3):

    HOST = '192.168.1.200'
    PORT = 65432        # Port to listen on (non-privileged ports are > 1023)
    FLAG = True
    #create the socket
    objetoSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    #store the socket connection parameters
    datos_servidor = (HOST, PORT)
    print('empezando a levantar %s puerto %s' % datos_servidor)
    #We associate server data to the socket
    objetoSocket.bind(datos_servidor)
    #We indicate to the socket the the number of incoming connections
    objetoSocket.listen(1)
    #We create a loop to never stop listen
    while FLAG:
      print('Esperando para realizar conexión')
      #To listen message we must accept the socket before
      connection, datos_cliente = objetoSocket.accept()
      try:
        print('conexión desde', datos_cliente)
        #Create loop to read data and when stop it will exit
        while True:
          data = connection.recv(1024)
          data_str = data.decode('utf8', 'strict').strip('\x00\x04')
          #servo.move_servo();
          if data:
             print('in: ', data_str)
             if("0x03" == data_str):
               print('Moviendo servo')
               servo.move_servo()
               connection.sendall(b'\x02')
             if("0x05" == data_str):
               print('Close connection')
               connection.sendall(b'\x02')
               FLAG = False;
               break
             else:
               connection.sendall(b'\x04')
          else:
            print('no hay mas datos', datos_cliente)
            break
      finally:
        connection.close()

标签: javapythonsocketsnetworking

解决方案


推荐阅读