我想創建一個服務器/客戶端在Python中使用套接字發送文本和其他媒體文件。 場景: -客戶端將主機,端口和文件名作爲參數並將文件發送到服務器。 錯誤描述: -嘗試執行下面的客戶端代碼,在與client.Getting下面的錯誤相同的目錄中有文本文件「tos」。從客戶端使用python套接字發送txt文件到服務器
**$ python Cli.py 127.0.0.1 5007 tos**
Traceback (most recent call last):
File "Cli.py", line 32, in <module>
client= Client(host,port,file)
File "Cli.py", line 15, in __init__
self.connect(file)
File "Cli.py", line 20, in connect
self.sendFile(file)
File "Cli.py", line 26, in sendFile
readByte = open(file, "rb")
**IOError: [Errno 2] No such file or directory: ''**
注意: - 還請描述是否有任何文件發送到服務器,搜索硬盤驅動器。
服務器: -
from socket import *
port = 5007
file = ''
class Server:
gate = socket(AF_INET, SOCK_STREAM)
host = '127.0.0.1'
def __init__(self, port):
self.port = port
self.gate.bind((self.host, self.port))
self.listen()
def listen(self):
self.gate.listen(10)
while True:
print("Listening for connections, on PORT: ", self.port)
add = self.gate.accept()
self.reciveFileName()
self.reciveFile()
def reciveFileName(self):
while True:
data = self.gate.recv(1024)
self.file = data
def reciveFile(self):
createFile = open("new_"+self.file, "wb")
while True:
data = self.gate.recv(1024)
createFile.write(data)
createFile.close()
server= Server(port)
listen()
客戶: -
#!/usr/bin/env python
from socket import *
host = ''
port = 5007
file = ''
class Client:
gateway = socket(AF_INET, SOCK_STREAM)
def __init__(self, host,port, file):
self.port = port
self.host = host
self.file = file
self.connect()
def connect(self):
self.gateway.connect((self.host, self.port))
self.sendFileName(file)
self.sendFile(file)
def sendFileName(self):
self.gateway.send("name:" +self.file)
def sendFile(self):
readByte = open(self.file, "rb")
data = readByte.read()
readByte.close()
self.gateway.send(data)
self.gateway.close()
client= Client(host,port,file)
connect()
你有沒有打算給這個文件命名? –
該場景是我不想硬編碼的文件名。而是希望客戶端程序通過命令行發送文件併發送它。 – Noddy
是的...但你沒有這樣做... –