簡體   English   中英

Python 套接字服務器,限制接收數據

[英]Python socket server, limiting data received

當嘗試將 sockets 的文件從 my.network 上的一台設備發送到另一台設備時,它會將數據限制為 2760 字節,並且不會在服務器端接收到整個文件

這是我在樹莓派上的服務器代碼:

import socket
import os

host = "my_ip"
port = "my_port"

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen()

def send(mess):
    con.send(bytes(mess, "utf-8"))

def receive():
    global message
    message = con.recv(22000).decode('utf-8')

while True:
    try:
        con, address = s.accept()
        print(f"Connection to {address} made successfully")
        receive()
        if message == "quit":
            break
        else:
            send("received")
            print(len(message))
            with open("file.py", 'w', encoding='utf-8')as a:
                a.write(message)
            os.system("python3 file.py")
    except:
        pass

這是我的客戶在另一台設備上的代碼

with open('file.py', 'r', encoding = 'utf-8')as f:
    python_file = f.read()

print(len(python_file))
#returns 20940
import socket

host = "my_ip"
port = my_port

def send(mess):
    s.send(bytes(mess, 'utf-8'))
    
def receive():
    message = s.recv(1024).decode('utf-8')
    print(message)
    
while True:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    send_it = input("Send File?[y/n]: ")
    if send_it == "y":
        try:
            s.connect((host, port))
            send(python_file)
            recieve()
        except:
            pass
    if send_it == "quit":
        try:
            s.connect((host, port))
            send(send_it)
            recieve()
        except:
            pass
    else:
        pass

當我取消 try 循環時,它不會給出任何錯誤或原因,說明為什么我只接收文件的一部分(2760 字節)。 它還會隨機(很少)發送超過 2760 個字節,或者有時會發送所有字節。 不過,它始終只發送 2760 個字節。

也許您想使用sendall()而不是send() 基本上sendall()保證將發送所有數據,除非引發異常,並且它是其他高級語言也提供的 python 功能。

為了接收發送的所有字節,最好使用循環來執行此操作:

data = bytearray(1)
# loop until there is no more data to receive.
while data:
   data = socket.recv(1024) # Receive 1024 bytes at a time.

關於send()sendall()之間的區別在 python here中有一個很好解釋的答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM