You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python Sockets定期发送更新后的JSON文件?

实现定时推送更新的JSON文件方案

针对你需要每10秒传输更新后JSON文件的需求,这里提供两种可行的实现方案,你可以根据场景选择:


方案一:长连接持续推送(推荐)

通过客户端与服务器保持一次连接,服务器每隔10秒主动推送最新的JSON文件内容,同时解决多轮推送的粘包问题。

修改后的Server.py

import socket
import time

json_file = r'position-info.json'

# 初始化Socket
sock = socket.socket()
print("Socket created successfully.")
port = 8800
host = ''
sock.bind((host, port))
sock.listen(10)
print('Socket is listening...')

def send_latest_file(conn):
    try:
        # 读取最新文件内容
        with open(json_file, 'rb') as file:
            file_content = file.read()
        # 先发送4字节的文件长度(大端编码),避免粘包
        file_len = len(file_content).to_bytes(4, byteorder='big')
        conn.send(file_len)
        # 发送完整文件内容
        conn.sendall(file_content)
        print('Latest file sent successfully.')
    except Exception as e:
        print(f'Error sending file: {e}')

while True:
    con, addr = sock.accept()
    print('Connected with ', addr)
    
    # 接收客户端问候
    data = con.recv(1024)
    print(data.decode())
    
    # 持续推送最新文件
    try:
        while True:
            send_latest_file(con)
            time.sleep(10)
    except (ConnectionResetError, BrokenPipeError):
        print(f'Connection with {addr} closed.')
        con.close()

修改后的Client.py

import socket
import time

port = 8800
host = 'localhost'

def receive_file(conn):
    # 先接收4字节的文件长度
    len_data = conn.recv(4)
    if not len_data:
        return None
    file_len = int.from_bytes(len_data, byteorder='big')
    # 按长度接收完整文件内容
    file_content = b''
    while len(file_content) < file_len:
        chunk = conn.recv(min(1024, file_len - len(file_content)))
        if not chunk:
            return None
        file_content += chunk
    return file_content

# 建立长连接
sock = socket.socket()
sock.connect((host, port))
print('Connection Established.')
sock.send('A message from the client'.encode())

try:
    while True:
        content = receive_file(sock)
        if content:
            # 保存文件或直接处理JSON内容
            with open('client-file.json', 'wb') as file:
                file.write(content)
            print('Latest file received successfully.')
        time.sleep(0.1)
except (ConnectionResetError, BrokenPipeError):
    print('Connection closed by server.')
finally:
    sock.close()
    print('Connection Closed.')

核心说明

  • 用文件长度前缀解决粘包问题,确保客户端能准确拆分每一次推送的文件数据
  • 服务器保持长连接,定时读取最新文件并推送,客户端持续接收更新
  • 增加异常捕获,处理连接断开时的程序崩溃问题

方案二:客户端定时轮询(简单易实现)

客户端每隔10秒重新连接服务器,获取最新文件内容,逻辑简单,无需修改原有服务器的单次传输逻辑。

修改后的Server.py(保持原逻辑即可)

import socket

json_file = r'position-info.json'

sock = socket.socket()
print("Socket created successfully.")
port = 8800
host = ''
sock.bind((host, port))
sock.listen(10)
print('Socket is listening...')

while True:
    con, addr = sock.accept()
    print('Connected with ', addr)

    data = con.recv(1024)
    print(data.decode())
    
    with open(json_file, 'rb') as file:
        line = file.read(1024)
        while line:
            con.send(line)
            line = file.read(1024)
    
    print('File has been transferred successfully.')
    con.close()

修改后的Client.py

import socket
import time

port = 8800
host = 'localhost'

def get_latest_file():
    sock = socket.socket()
    try:
        sock.connect((host, port))
        print('Connection Established.')
        sock.send('A message from the client'.encode())

        with open('client-file.json', 'wb') as file:
            line = sock.recv(1024)
            while line:
                file.write(line)
                line = sock.recv(1024)
        print('File has been received successfully.')
    except Exception as e:
        print(f'Error receiving file: {e}')
    finally:
        sock.close()
        print('Connection Closed.')

# 每隔10秒发起一次请求
while True:
    get_latest_file()
    time.sleep(10)

核心说明

  • 客户端定时创建新连接获取文件,逻辑简单,无需维护长连接
  • 服务器保持原有单次文件传输逻辑,兼容性好

内容的提问来源于stack exchange,提问作者cappo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 08:47:34