java - 客户端/服务器套接字不适用于外部连接
问题描述
我用 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()
解决方案
推荐阅读
- python - 一切正常,但随后发送部分不起作用。click() 在硒中不起作用
- excel - 将数据从 1 个 excel 传输到另一个 excel 的宏
- firebase - 如何获取添加到 Firestore 的文档的 ID 号?
- java - mapstruct v1.3.1FINAL:不生成来自静态方法的导入
- jmeter - Is it possible to generate jmeter html report using properties file as parameter using command line query
- mips - 单周期 mips verilog 实现的程序计数器调试
- callback - 使用 dcc.DatePickerRange 在 Plotly Express 中进行多输入回调
- html - 在 SQL Server 中从 XML 创建 HTML 表
- reactjs - 如何在另一个 redux-saga 结束时调用一个 saga,就像 redux-thunk 中的异步等待一样
- javascript - 在 useEffect 内的 React Hooks 中安排作业