Python 3.x OSError:[Errno 22]udp连接的参数无效

Python 3.x OSError:[Errno 22]udp连接的参数无效,python-3.x,network-programming,Python 3.x,Network Programming,本地pc上的udp服务器和客户端 cat server.py import socket MAX_BYTES =65535 def server(): sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) sock.bind(('127.0.0.1',10000)) print('Listening at {}'.format(sock.getsockname())) while True:

本地pc上的udp服务器和客户端

cat server.py
import socket
MAX_BYTES =65535

def server():
    sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    sock.bind(('127.0.0.1',10000))
    print('Listening at {}'.format(sock.getsockname()))
    while True:
        data,address = sock.recvfrom(MAX_BYTES)
        text = data.decode('ascii')
        print('The client at {} says {!r} '.format(address,text))

if __name__ == "__main__":
    server()
将端口
10000
与本地主机绑定-
127.0.0.1
,并侦听从客户端发送的消息

cat client.py
import socket
import time
from datetime import datetime
MAX_BYTES =65535

def client():
    sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    sock.bind(('127.0.0.1',10001))
    text = 'The time is {}'.format(datetime.now())
    data = text.encode('ascii')
    while True:
        time.sleep(10)
        sock.sendto(data,('127.0.0.1',10000))
        print('The OS assinged me the address {}'.format(sock.getsockname()))

if __name__ == "__main__":
    client()
在本地pc上运行server.py和client.py,服务器可以接收客户端发送的消息

现在,我用远程vps_ip在client.py中的行中更改了
127.0.0.1

sock.sendto(data,('127.0.0.1',10000))
进入

将server.py推入我的vps。在本地pc上启动client.py,在远程vps上启动server.py,然后全部启动。 在我的客户端中,出现错误信息:

  File "client.py", line 13, in client
    sock.sendto(data,('remote_ip',10000))
OSError: [Errno 22] Invalid argument

如何使远程ip接收从本地客户端pc发送的消息?

可能会发生两件事:

  • 您没有正确地传递远程IP。确保您没有按字面意思传递“远程ip”,并将其替换为服务器的有效IPv4 ip地址字符串(即:
    '192.168.0.100'
    )。(仅供参考,从技术上讲,您只需在服务器上放置
    '0.0.0'
    即可监听所有IP地址)
  • 您仍然可以将客户端绑定到本地地址(127.0.0.1),但将目标设置为有效的外部地址(192.168.0.100)。删除
    套接字。在客户端绑定
    行代码来测试它,您不需要它
    
    如果两者都不起作用,则添加在客户端上运行并以服务器为目标的
    ping
    命令的结果

    您的
    'remote\u ip'
    是字面上的
    'remote\u ip'
    ,还是实际上是一个ip地址或主机名?它是一个真实的ip地址,而不是主机名。
      File "client.py", line 13, in client
        sock.sendto(data,('remote_ip',10000))
    OSError: [Errno 22] Invalid argument