You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Python跨远程服务器通信?现有代码跨主机连接失败

Fixing Cross-Remote-Server Connection Issues for Your Socket Chat App

I see the issue here — your current code works locally because it's using loopback/local network interfaces, but when trying to connect across remote servers, there are a few key adjustments needed. Let's break down the problems and fix them step by step.

Key Problems Preventing Cross-Server Connections

  • Server only listens on local interfaces: Your server binds to host_name, which resolves to the server's local IP (like 127.0.0.1 or a private LAN IP). This means it won't accept connections from outside the server itself.
  • Firewall/port restrictions: Most remote servers have firewalls that block incoming connections on non-standard ports (like 1234). You'll need to open this port on your server's firewall and cloud security groups (if applicable).
  • Client uses the wrong IP: When connecting remotely, the client needs to use the server's public IP address, not its local hostname or private IP.

Modified Server Code (serv.py)

The critical change here is binding to 0.0.0.0 instead of the local hostname — this tells the server to listen on all available network interfaces, allowing remote connections.

import time, socket, sys
print('Setup Server...')
time.sleep(1)
# Get the hostname, IP Address from socket and set Port
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host_name = socket.gethostname()
ip = socket.gethostbyname(host_name)
port = 1234
# Bind to 0.0.0.0 to listen on all interfaces (critical for remote connections)
soc.bind(('0.0.0.0', port))
print(host_name, '({})'.format(ip))
name = input('Enter name: ')
soc.listen(1)
# Try to locate using socket
print('Waiting for incoming connections...')
connection, addr = soc.accept()
print("Received connection from ", addr[0], "(", addr[1], ")\n")
print('Connection Established. Connected From: {}, ({})'.format(addr[0], addr[0]))
# Get a connection from client side
client_name = connection.recv(1024)
client_name = client_name.decode()
print(client_name + ' has connected.')
print('Press [bye] to leave the chat room')
connection.send(name.encode())
while True:
    message = input('Me > ')
    if message == 'bye':
        message = 'Good Night...'
        connection.send(message.encode())
        print("\n")
        break
    connection.send(message.encode())
    message = connection.recv(1024)
    message = message.decode()
    print(client_name, '>', message)

Modified Client Code (clie.py)

No major code changes here, but I updated the prompt to clarify that you need to input the server's public IP (a common point of confusion).

import time, socket, sys
print('Client Starting...')
time.sleep(1)
# Get the hostname, IP Address from socket and set Port
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
shost = socket.gethostname()
ip = socket.gethostbyname(shost)
# Get information to connect with the server
print(shost, '({})'.format(ip))
# Updated prompt to clarify public IP requirement
server_host = input('Enter server\'s PUBLIC IP address:')
name = input('Enter Client\'s name: ')
port = 1234
print('Trying to connect to the server: {}, ({})'.format(server_host, port))
time.sleep(1)
soc.connect((server_host, port))
print("Connected...\n")
soc.send(name.encode())
server_name = soc.recv(1024)
server_name = server_name.decode()
print('{} has joined...'.format(server_name))
print('Enter [bye] to exit.')
while True:
    message = soc.recv(1024)
    message = message.decode()
    print(server_name, ">", message)
    message = input(str("Me > "))
    if message == "bye":
        message = "Leaving the Chat room"
        soc.send(message.encode())
        print("\n")
        break
    soc.send(message.encode())

Additional Steps to Ensure It Works

  1. Open port 1234 on your server's firewall:
    • For Linux servers using UFW: Run sudo ufw allow 1234/tcp
    • For cloud providers (AWS, Azure, GCP): Add an inbound rule to your security group allowing TCP traffic on port 1234 from your client's IP (or all IPs for testing).
  2. Find your server's public IP:
    • On the server, run curl ifconfig.me to get its public IP address.
  3. Test the flow:
    • Start serv.py on your remote server first.
    • Run clie.py on your local machine, enter the server's public IP when prompted, and you should be able to send/receive messages across servers.

内容的提问来源于stack exchange,提问作者deval LazzyDevs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:50:58