我正在学习python中的socket programming
客户端服务器体系结构。我制作了此程序,以从客户端到服务器一个接一个地发送多个文件。客户端程序查询用户以键入文件名,然后将该名称发送给服务器,服务器在服务器上以附加+二进制方式打开具有该名称的新文件。但是很明显,服务器仅在第一次创建新文件,而在其他时候没有。它只是将下一个文件追加到现有文件中。请看一下。
#server.py
from socket import *
HOST = ''
PORT = 32000
ADDRESS = (HOST, PORT)
BUFF_SIZE = 1024
tcpServerSocket = socket(AF_INET, SOCK_STREAM)
tcpServerSocket.bind(ADDRESS)
tcpServerSocket.listen(5)
print("waiting for connection..")
client, addr = tcpServerSocket.accept()
print("connected with {}".format(addr))
name = client.recv(BUFF_SIZE).decode()
while True:
if not name:
break
f = open(name, 'ab')
data = client.recv(BUFF_SIZE)
while data:
f.write(data)
data = client.recv(BUFF_SIZE)
f.close()
name = client.recv(BUFF_SIZE)
name = name.decode()
tcpServerSocket.close()
这是client.py
from socket import *
HOST = "localhost"
PORT = 32000
ADDRESS = (HOST, PORT)
BUFF_SIZE = 1024
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect(ADDRESS)
while True:
name = input("please enter file name: \n")
clientSocket.send(name.encode())
if not name:
break
f = open(name, 'rb')
data = f.read(BUFF_SIZE)
while data:
clientSocket.send(data)
data = f.read(BUFF_SIZE)
f.close()
choice = input("Do you wanna send another file: y/n ?")
if choice.lower() != 'y':
clientSocket.send("".encode())
break
clientSocket.close()
我想知道是否有一种类似函数的冲洗方法,该方法可以完全关闭现有文件/流并每次创建一个新文件。
答案 0 :(得分:0)
我这是问题所在。我没有尝试过。在While真循环内将新文件命名为
#server.py
from socket import *
HOST = ''
PORT = 32000
ADDRESS = (HOST, PORT)
BUFF_SIZE = 1024
tcpServerSocket = socket(AF_INET, SOCK_STREAM)
tcpServerSocket.bind(ADDRESS)
tcpServerSocket.listen(5)
print("waiting for connection..")
client, addr = tcpServerSocket.accept()
print("connected with {}".format(addr))
while True:
name = client.recv(BUFF_SIZE).decode()
if not name:
break
f = open(name, 'ab')
data = client.recv(BUFF_SIZE)
while data:
f.write(data)
data = client.recv(BUFF_SIZE)
f.close()
name = client.recv(BUFF_SIZE)
name = name.decode()
tcpServerSocket.close()