在Python中使用asyncio?

bgibtngc  于 2023-08-08  发布在  Python
关注(0)|答案(1)|浏览(69)

在下面的代码中:

import socket

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

server_address = ('127.0.0.1', 8000)
server_socket.bind(server_address)
server_socket.listen()

try:
    connection, client_address = server_socket.accept()
    print(f'I got a connection from {client_address}!')

    buffer = b''

    while buffer[-2:] != b'\r\n':
        data = connection.recv(2)
        if not data:
            break
        else:
            print(f'I got data: {data}!')
            buffer = buffer + data

    print(f"All the data is: {buffer}")
finally:
    server_socket.close()

字符串
我想应该是以下几点

I got a connection from ('127.0.0.1', 49721)!
I got data: b'te'!
I got data: b'st'!
I got data: b'in'!
I got data: b'g1'!
I got data: b'\r\n'!
All the data is: b'testing1\r\n'


但我得到的是

I got a connection from ('127.0.0.1', 49721)!
I got data: b't'!
I got data: b'e'!
I got data: b's'!
I got data: b't'!
I got data: b'i'!
I got data: b'n'!
I got data: b'g'!
I got data: b'1'!
I got data: b'\r\n'!
All the data is: b'testing1\r\n'


recv方法从客户端套接字接收最多2个字节的数据,并将数据作为bytes对象返回。如果这是它的作用,为什么它不工作,或者有什么我误解了?

vtwuwzda

vtwuwzda1#

您的.recv(2)接收最多2个字节。它不会等待2。
如果你一个字节一个字节地发送数据,它将返回它。
一个典型的循环会重试recv(),直到你有了所有的数据或者recv()是空的,这表明一个关闭的连接。

相关问题