请帮助我,我只是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')
Blockquote
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()
名称的输出文件为receive_file,不带扩展名。
答案 0 :(得分:0)
您需要定义一个协议,该协议先传输文件名,然后传输数据。这是一个将input.txt
的内容作为文件名output.txt
发送到客户端的示例。客户端读取文件名,然后将数据写入该文件名。我这样做是因为客户端和服务器运行在同一台计算机上,并且在同一目录中读取/写入文件。
server.py
import socketserver
class MyTCPHandler(socketserver.BaseRequestHandler):
def handle(self):
filename = 'output.txt'
self.request.sendall(filename.encode() + b'\r\n')
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'\r\n').decode()
with open(filename,'wb') as out:
out.write(f.read())