请帮助我,我只是python的初学者,我想学习这个。我不知道如何从服务器部分获取原始文件名和扩展名。
我尝试了很多方法和研究,但仍然无法工作。我见过许多类型的例子,这些示例只能在客户端部分上传带有with open('received_file','.txt','wb') as f:
的文本文件,而不能上传文件的多种类型扩展名。我知道因为'.txt'
所以只为文本文件工作。我不知道如何声明以获取多个扩展名和原始文件名。这是我的原始代码。
client
import socket
import os
TCP_IP = 'localhost'
TCP_PORT = 9001
BUFFER_SIZE = 8192
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
#data = s.recv(BUFFER_SIZE)
with open('received_file','.txt','wb') as f:
print ('file opened')
while True:
print('receiving data...')
data = s.recv(BUFFER_SIZE)
print('data=%s', (data))
if not data:
f.close()
print ('file close()')
break
# write data to a file
f.write(data)
print('Successfully get the file')
s.close()
print('connection closed')
块引用
server
import socket
from threading import Thread
from socketserver import ThreadingMixIn
import tkinter
import tkinter.filedialog
TCP_IP = 'localhost'
TCP_PORT = 9001
BUFFER_SIZE = 8192
tkinter.Tk().withdraw()
in_path = tkinter.filedialog.askopenfilename( )
class ClientThread(Thread):
def __init__(self,ip,port,sock):
Thread.__init__(self)
self.ip = ip
self.port = port
self.sock = sock
print (" New thread started for "+ip+":"+str(port))
def run(self):
filename= in_path
f = open(filename,'rb')
while True:
l = f.read(BUFFER_SIZE)
while (l):
self.sock.send(l)
l = f.read(BUFFER_SIZE)
if not l:
f.close()
self.sock.close()
break
tcpsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
tcpsock.bind((TCP_IP, TCP_PORT))
threads = []
while True:
tcpsock.listen(5)
print ("Waiting for incoming connections...")
(conn, (ip,port)) = tcpsock.accept()
print ('Got connection from ', (ip,port))
newthread = ClientThread(ip,port,conn)
newthread.start()
threads.append(newthread)
for t in threads:
t.join()
名称的输出文件received_file不带扩展名。
您需要定义一个协议来传输文件名,然后传输数据。 下面是一个示例,它将input.txt
的内容作为文件名传输到客户端output.txt
。 客户端读取文件名,然后将数据写入该文件名。 我这样做只是因为客户端和服务器在同一台计算机上运行,并且在同一目录中读/写文件。
server.py
import socketserver
class MyTCPHandler(socketserver.BaseRequestHandler):
def handle(self):
filename = 'output.txt'
self.request.sendall(filename.encode() + b'rn')
with open('input.txt','rb') as f:
self.request.sendall(f.read())
if __name__ == "__main__":
HOST, PORT = "localhost", 9001
with socketserver.ThreadingTCPServer((HOST, PORT), MyTCPHandler) as server:
server.serve_forever()
client.py
import socket
import os
SERVER = 'localhost',9001
s = socket.socket()
s.connect(SERVER)
# autoclose f and s when with block is exited.
# makefile treats the socket as a file stream.
# Open in binary mode so the bytes of the file are received as is.
with s,s.makefile('rb') as f:
# The first line is the UTF-8-encoded filename. Strip the line delimiters.
filename = f.readline().rstrip(b'rn').decode()
with open(filename,'wb') as out:
out.write(f.read())