Python UDP客户端 - 服务器具有不同的匹配传入 - 传出端口

时间:2017-10-25 16:47:02

标签: python-3.x sockets udp

基于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)应该等待传入的数据? 我在这里缺少什么?

1 个答案:

答案 0 :(得分:0)

该死的......刚看到它。愚蠢的错误。在循环内的客户端中调用 int main() { Vector vecStore; for(int i = 0; i < 1000; i++) { long a; vecStore.add(a = i + 1); } cout << "GET DATA _________ :: " << endl; vecStore.getData(); return 0; }