服務器.py:
這里使用來自 NVD 的 json 檔案
import socket, json, random, threading, zipfile, requests, re, zipfile
from bs4 import BeautifulSoup
from zipfile import *
def listen_user(user):
for x in range(2018,2021,1):
filename = "nvdcve-1.1-" str(x) ".json"
print(filename)
with open(filename, 'rb') as file:
sendfile = file.read()
user.sendall(sendfile)
print('file sent' str(x))
def start_server():
while True:
user_socket, address = server.accept()
print(f"User <{address[0]}> connected!")
users.append(user_socket)
listen_accepted_user = threading.Thread(
target=listen_user,
args=(user_socket,)
)
listen_accepted_user.start()
if __name__ == '__main__':
users = []
server = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
)
server.bind(
("127.0.0.1", 100)
)
server.listen(5)
print('waiting for connection...')
start_server()
客戶端.py
import socket, json, random
from threading import Thread
def start_client(client):
savefilename = str(random.randint(1,10)) 'new.json'
print(savefilename)
with client,open(savefilename,'wb') as file:
while True:
recvfile = client.recv(4096)
if not recvfile:
print('1 client')
break
file.write(recvfile)
file.close()
print('2 client')
client.close()
if __name__ == '__main__':
client = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
)
client.connect(
("127.0.0.1", 100)
)
start_client(client)
當我發送檔案時 - 它們幾乎全部發送,但程式沒有到達“列印('1個客戶端')”或“列印('2個客戶端')”行
并且 *new 檔案包含除最后幾行之外的所有行
請幫忙 - 如何修復代碼?
uj5u.com熱心網友回復:
recvfile = client.recv(4096)在 while 回圈中,它一直在等待接收下一個位元組。客戶端不知道檔案已發送,因此它等待下一個 4096 位元組并且不退出回圈。
要讓客戶端知道檔案傳輸已完成,您可以從 server.py 發送一條訊息,您可以在客戶端中驗證該訊息并打破回圈,如下所示。
服務器.py
def listen_user(user):
for x in ["f.json","g.json"]:
filename = x
print(filename)
with open(filename, 'rb') as file:
sendfile = file.read()
user.sendall(sendfile)
print('file sent' str(x))
user.send(b"Done")
客戶端.py
def start_client(client):
savefilename = str(random.randint(1,10)) 'new.json'
print(savefilename)
with client,open(savefilename,'wb') as file:
while True:
recvfile = client.recv(4096)
if recvfile.decode("utf-8") =="Done":
print('1 client')
file.close()
break
file.write(recvfile)
print('2 client')
client.close()
uj5u.com熱心網友回復:
該呼叫client.recv(4096)意味著您正在等待接收 4096 個位元組,然后對這些位元組執行某些操作。在這種情況下可能發生的情況是您正在寫出所有位元組,減去那些最后沒有完全填滿緩沖區的位元組。這讓客戶端等待一個緩沖區,該緩沖區的空間認為它尚未準備好寫出。
我猜你假設client.recv()一旦你獲得了所有的資料就會回傳一個空字串;根據您的代碼,情況并非如此。如果您希望客戶端能夠終止連接,您將需要發送某種控制序列或嘗試以其他方式評估從服務器接收的位元組以確定何時關閉連接。如果這樣做,您可能希望bufsize在呼叫時設定client.recv()為 1,而是在寫入檔案之前使用其他方法進行緩沖。
例如,由于您正在發送 JSON 資料,您可以將位元組連接到一個變數,然后反復嘗試決議 JSON。成功決議 JSON 后,您可以終止客戶端的連接(盡管這意味著您必須為每個發送的檔案打開一個新連接)。
但是,這提出了一個問題:為什么需要從客戶端關閉?通常服務器會在發送完所有相關資料后關閉連接。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/313384.html
下一篇:客戶端斷開或關閉
