Python Socket - ValueError: too many values to unpack (expected 2)

Python Socket - ValueError: too many values to unpack (expected 2)

我遇到的问题是套接字只接收数据,而不是地址,所以我无法向原始发件人发送诸如确认之类的数据包。我正在用发送者和接收者实现一个 go-back-N。 这是错误:

Traceback (most recent call last):
  File "./netster.py", line 128, in <module>
    main()
  File "./netster.py", line 120, in main
    run_server(args.host, int(args.port), udp=args.udp, rudp = args.rudp, filename=f) 
  File "./netster.py", line 27, in run_server
    rudp_gobackn_recv(port, kwargs['filename'])
  File "/Users/a3.py", line 352, in rudp_gobackn_recv
    data, client_address = serversocket.recv(1500)
ValueError: too many values to unpack (expected 2)

这是接收方的代码片段,展示了我如何初始化数据包和接收数据。

serversocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
serversocket.bind(('localhost', port))
...
data, client_address = serversocket.recv(1500)

这是我设置发送方套接字的方式:

clientsocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_address = (host, port)

发送方和接收方的地址和端口都为

('localhost', 1234)

1234 是任意端口号。 以下是我如何设置要发送的数据包,以防万一,以及我是如何发送的。

for x in range(len(window), window_size):
            data = file.read(data_size)
            if not data:
                end_bit = '1'
            decoded_data = data.decode('utf-8')
            packet = str(nextseqnum) + "@@" + str(end_bit) + "@@" + str(decoded_data)
            nextseqnum = str(int(nextseqnum) + 1)
            window.append(packet)
            if not data:
                break

这是我发送的方式:

for y in range(0, len(window)):
            print("Window: ", window)
            print("PACKET!!!!", window[y])
            packet = window[y]
            p = packet.encode('utf-8')
            print("Socket ouput: ", clientsocket.sendto(p, server_address))
            if(y == 0):
                oldest_time = time.time()

如果我更改接收器代码使其可以编译为:

data  = serversocket.recv(1500)

事物的发送方打印出来:

Window:  ['1@@0@@abcdefghijklmnopqrstuvwxyz\n', '2@@1@@']
PACKET!!!! 1@@0@@abcdefghijklmnopqrstuvwxyz

Socket ouput:  33
Window:  ['1@@0@@abcdefghijklmnopqrstuvwxyz\n', '2@@1@@']
PACKET!!!! 2@@1@@
Socket ouput:  6

想知道为什么它只发送数据而不发送服务器地址吗?我已经研究了这个问题,但没有成功,也调试了一段时间。

serversocket.recv(1500) 只有 returns 个字节,而不是 data, client_address。您正在寻找 recvfrom.

这会让您明白为什么会出现错误:

>>> data, client_address = b"hello"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)
>>> a, b, c, d, e = b"hello"
>>> a, b, c, d, e
(104, 101, 108, 108, 111)