TCP在不关闭socket的情况下传输文件

TCP transfer files without closing socket

我编写了一个简单的 TCP 服务器 - 客户端文件共享,但它仅在脚本关闭客户端套接字时有效。

我试图删除客户端 python 脚本中的 s.close,但它给了我一个错误。任何的想法? 我不知道是否可以在不关闭套接字的情况下使用 TCP 执行此类操作。

这是我的代码

server.py

import socket
import tqdm
import os

SERVER_HOST = "192.168.1.48"
SERVER_PORT = 5001

BUFFER_SIZE = 4096
SEPARATOR = "<SEPARATOR>"

s = socket.socket()
s.bind((SERVER_HOST, SERVER_PORT))

s.listen(5)
print(f"[*] Listening as {SERVER_HOST}:{SERVER_PORT}")

client_socket, address = s.accept()

print(f"[+] {address} is connected.")


def receive_file(filename):

    received = client_socket.recv(BUFFER_SIZE).decode()
    filename, filesize = received.split(SEPARATOR)
 
    filename = os.path.basename(filename)
  
    filesize = int(filesize)

    progress = tqdm.tqdm(range(filesize), f"Receiving {filename}", unit="B", unit_scale=True, unit_divisor=1024)
    with open(filename, "wb") as f:
        while True:
            # read 1024 bytes from the socket (receive)
            bytes_read = client_socket.recv(BUFFER_SIZE)
            if not bytes_read:
                # nothing is received
                # file transmitting is done
                break
            # write to the file the bytes we just received
            f.write(bytes_read)
            # update the progress bar
            progress.update(len(bytes_read))

while True:
    command = input("-->")
    client_socket.send(str.encode(command))
    filename = command[9:]
    receive_file(filename)
    

client.py

import socket
import tqdm
import os

SEPARATOR = "<SEPARATOR>"
BUFFER_SIZE = 4096 # send 4096 bytes each time step



host = "192.168.1.48"

port = 5001

filesize = os.path.getsize(filename)
s = socket.socket()

print(f"[+] Connecting to {host}:{port}")
s.connect((host, port))
print("[+] Connected.")

def send_file(filename,filesize):

    s.send(f"{filename}{SEPARATOR}{filesize}".encode())

   
    progress = tqdm.tqdm(range(filesize), f"Sending {filename}", unit="B", unit_scale=True, unit_divisor=1024)
    with open(filename, "rb") as f:
        while True:
            
            bytes_read = f.read(BUFFER_SIZE)
            if not bytes_read:
                # file transmitting is done
                break
          
            s.sendall(bytes_read)
       
            progress.update(len(bytes_read))
    # close the socket
    s.close()


while True:
    command = s.recv(4096)
    if command[:8].decode("utf-8") == "download":
        print("yes it start")
        filename = command[9:].decode("utf-8")
        print(filename)
        filesize = os.path.getsize(filename)
        send_file(filename,filesize)

收到 filesize 字节后跳出循环。

    with open(filename, "wb") as f:
        total_bytes = 0
        while total_bytes < filesize:
            # read 1024 bytes from the socket (receive)
            bytes_read = client_socket.recv(BUFFER_SIZE)
            if not bytes_read:
                # nothing is received
                # file transmitting is done
                break
            # write to the file the bytes we just received
            f.write(bytes_read)
            total_bytes += len(bytes_read)
            # update the progress bar
            progress.update(len(bytes_read))