【问题标题】:Python UDP client-server with different matching incoming-outgoing ports具有不同匹配传入传出端口的 Python UDP 客户端-服务器
【发布时间】:2018-04-06 20:49:50
【问题描述】:

基于http://www.binarytides.com/programming-udp-sockets-in-python/ 的示例,我对其进行了修改以在 python 3 上运行,并在客户端和服务器上使用了两个相反的端口,因此每个人的回复都转到这些端口。这是我的例子

服务器:

'''
    Simple udp socket server
'''

import socket
import sys

HOST = 'localhost'
PORT_IN = 8889  # Arbitrary non-privileged port
PORT_OUT = 8888

# Datagram (udp) socket
try :
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    print('Socket created')
except socket.error as e:
    print(e)
    sys.exit()


# Bind socket to local host and port
try:
    s.bind((HOST, PORT_IN))
except socket.error as e:
    print(e)
    sys.exit()

print('Socket bind complete')

#now keep talking with the client
while 1:
    # receive data from client (data, addr)
    d = s.recvfrom(1024)
    data = d[0]
    addr = d[1]

    if not data:
        break

    reply = 'OK...' + str(data)

    s.sendto(reply.encode('UTF-8'), ('localhost', PORT_OUT))
    print('Message[' + addr[0] + ':' + str(addr[1]) + '] - ' + str(data).strip())

s.close()

客户:

'''
    udp socket client
    Silver Moon
'''

import socket   #for sockets
import sys  #for exit

# create dgram udp socket
try:
    s1 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s2 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
except socket.error:
    print('Failed to create socket')
    sys.exit()

host = 'localhost'
port_out = 8889
port_in = 8888

counter = 0
while(1) :
    # msg = b'aoua'
    msg = 'aoua' + str(counter)

    try :
        #Set the whole string
        s1.sendto(msg.encode('UTF-8'), (host, port_out))

        # receive data from client (data, addr)
        s2.bind(('localhost', port_in))
        d = s2.recvfrom(1472)
        reply = d[0]
        addr = d[1]

        print('Server reply : ' + str(reply))

    except socket.error as e:
        print(e)
        # sys.exit()
    counter += 1

问题在于客户端无法接收来自服务器的任何响应并且d = s2.recvfrom(1472) 挂起并出现错误[WinError 10022] An invalid argument was supplied。 我注意到sock.settimeout(seconds) 的行为略有不同,但我真的不知道为什么。 d = s2.recvfrom(buffer) 不应该等待传入数据吗? 我在这里错过了什么?

【问题讨论】:

    标签: python-3.x sockets udp


    【解决方案1】:

    该死的……刚看到。愚蠢的错误。在循环内的 Client 中调用 s2.bind(('localhost', port_in))

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-22
      • 1970-01-01
      • 1970-01-01
      • 2015-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-04
      相关资源
      最近更新 更多