我正在使用 python 3.6 和 ubuntu 18.04。
我能够使用socket-python(以二进制模式)发送单个音乐文件,并且我想将多个音乐文件从服务器发送到客户端。
问题是,在接收端(即客户端),所有音乐文件(从服务器发送的大约 120 个文件)都收集在一个文件中,使其成为一个 9 小时长的单个音乐文件。
我尝试使用 time.sleep 方法(不起作用),尝试发送虚假元素(显示错误)并尝试发送一些随机字符以在客户端结束文件写入并启动新文件写入(但随机字符需要编码和解码,因此再次出错,因为二进制数据无法解码)。
服务器代码
import socket
import os
import send_file
import time
s = socket.socket()
host = ""
port = 9997
s.bind((host, port))
s.listen(5)
print("Binding Done\n")
socket_object, address = s.accept()
print("Connection Established\n")
print("Sending file...")
file_class = send_file.send_files() #ignore
file_names = file_class.files #ignore - contains list of path of music file
socket_object.sendall( str(len(file_names)).encode() )
for i in file_names:
f = open(i, 'rb')
buf = f.read(1024)
while buf:
socket_object.sendall(buf)
buf = f.read(1024)
f.close()
print("Files Send")
socket_object.close()
s.close()
客户代码
import socket
import os
import time
def recv_file(i):
f = open("/home/ravi/PycharmProjects/File_Transfer/B/"+"M"+str(i)+".mp3", 'wb')
buf = s.recv(1024)
while buf:
f.write(buf)
buf = s.recv(1024)
f.close()
s = socket.socket()
host = "127.0.0.1"
port = 9997
s.connect((host, port))
print("Receiving data...")
l = s.recv(1024).decode() #ignore - length of total number of files i.e., 120 approx
for i in range(int(l)):
recv_file(i+1)
print("Files Collected")
s.close()
任何建议,将不胜感激。谢谢你。