在Python中如何触发网络缓冲区刷新?

0 投票
0 回答
16 浏览
提问于 2025-04-12 03:57

在苹果电脑上,我使用的是Python 3.9.10,利用socket的sendall方法通过网络连接向服务器发送数据。奇怪的是,发送的数据在我调用socket的close方法之前,服务器根本收不到,只有在我放弃等待返回数据时才会看到这些数据。

我的目的是让这个Python脚本作为一个网络客户端,去联系一个服务器并进行一些简单的数据交换。这个服务器是在一台运行Linux的机器上。客户端的脚本会启动一个线程来处理网络通信。

import threading, sys

t = threading.Thread(target=social_init, daemon=True)
t.start()

相关的代码部分是:

import socket               # Import socket module and JSON parser module
import json
def social_init():
    global social1_resps, social2_resps, social3_resps
    host = "test.mydomain.com"  # Get server name
    port = 6942                 # this is where the server is listening
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.settimeout(30.0)    # note: 30 second timeout
        s.connect((host, port))
        sbuf = json.dumps({"rmv":"1","gameID":9,"function":1})
        bbuf = sbuf.encode('utf-8')
        nbytes = len(bbuf)
        s.sendall(nbytes.to_bytes(4, 'little'))
        s.sendall(bbuf)

        nnbuf = s.recv(4)
        nbytes = int.from_bytes(nnbuf, 'little')
        bbuf = s.recv(nbytes)
        sbuf = str(bbuf, 'utf-8')
        obj = json.loads(sbuf)
        while (obj != None):
            # actual processing of returned data elided

        s.close()                   # Close the socket when done

这段代码在Windows和Linux上都能正常工作,但在苹果电脑上,服务器虽然能看到连接建立,但却收不到任何数据。当客户端等待接收数据超时,或者脚本结束(这会强制关闭连接)时,我们才会看到数据被发送出去——我通过在服务器上运行Wireshark检查了时间。

我知道有flush()这个函数,但因为我们使用的是socket而不是文件处理,所以flush似乎不适用。有没有什么方法可以在socket上强制刷新网络缓冲区呢?

0 个回答

暂无回答

撰写回答