使用 Python 套接字通过网络发送更新的文件

问题描述 投票:0回答:1

我正在尝试通过网络以 JSON 文件发送一些数据。该文件将定期更新(每 10 秒),我需要阅读该文件并使其在我的应用程序中可用。目前,我有一个客户端/服务器场景,我可以通过网络发送单个文件,但是当文件在 10 秒后更新时我正在努力解决该问题。文件最初发送正常,但我不确定如何处理更新的文件。

我的代码如下: 服务器.py:

import socket

# File to transfer
json_file = r'position-info.json'


# Initialize Socket Instance
sock = socket.socket()
print ("Socket created successfully.")

# Defining port and host
port = 8800
host = ''

# binding to the host and port
sock.bind((host, port))

# Listening
sock.listen(10)
print('Socket is listening...')

while True:
    # Establish connection with the clients.
    con, addr = sock.accept()
    print('Connected with ', addr)

    # Get data from the client
    data = con.recv(1024)
    print(data.decode())
    # Read File in binary
    file = open(json_file, 'rb')
    line = file.read(1024)
    # Keep sending data to the client
    while(line):
        con.send(line)
        line = file.read(1024)
    
    file.close()
    print('File has been transferred successfully.')

    con.close()

在客户端我有这个: 客户端.py:

import socket

# Initialize Socket Instance
sock = socket.socket()
print ("Socket created successfully.")

# Defining port and host
port = 8800
host = 'localhost'

# Connect socket to the host and port
sock.connect((host, port))
print('Connection Established.')
# Send a greeting to the server
sock.send('A message from the client'.encode())

# Write File in binary
file = open('client-file.txt', 'wb')

# Keep receiving data from the server
line = sock.recv(1024)

while(line):
    file.write(line)
    line = sock.recv(1024)
    print(line)
print('File has been received successfully.')
print(file)
file.close()
sock.close()
print('Connection Closed.')

对于发送单个文件,这可以正常工作。但是,我想在文件更新后每 10 秒发送一次文件。我该怎么做呢? 非常感谢

python sockets file-transfer
1个回答
0
投票

套接字是字节流,因此需要一个协议来将返回的字节解释为完整的消息。

缓冲收到的数据,直到收到完整的消息。

可以使用已知的分隔符(例如换行符或空值)来确定完整的消息,或者在消息前面加上消息的大小。由你决定。大小可以是“4 字节小端整数”或“ASCII 数字后跟换行符”或您决定的任何内容。

socket.makefile是一种缓冲数据的方法。它将套接字包装在类似文件的对象中,其中可以使用

.read()
.readline()
等方法来简化缓冲。

以下示例将 JSON 作为每条消息的单个换行符终止行发送。请注意,输入 JSON 可能包含换行符,但文件在解析和发送时没有任何缩进或换行符,因此可以通过发送 JSON 时添加的换行符来确定消息。

服务器:

import socket
import json
import time

with socket.socket() as sock:
    sock.bind(('', 8800))
    sock.listen()
    con, addr = sock.accept()
    print(f'{addr}: connected')
    with con:
        while True:
            with open('position-info.json', 'rb') as file:
                data = json.load(file)
            con.sendall(json.dumps(data).encode() + b'\n')
            print(f'{addr}: sent updated file')
            time.sleep(10)

客户:

import socket
import json

with socket.socket() as sock:
    sock.connect(('localhost', 8800))
    with sock, sock.makefile('rb') as infile:
        while True:
            line = infile.readline()
            if not line: break
            data = json.loads(line)
            print(data)
© www.soinside.com 2019 - 2024. All rights reserved.