我正在尝试使用套接字在 python 中创建一个服务器/客户端来发送文本和其他媒体文件。 场景:-客户端将主机、端口和文件名作为参数并将文件发送到服务器。 错误描述:-在尝试执行以下客户端代码时,文本文件“tos”与客户端位于同一目录中。出现以下错误。
**$ 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()