我试图用python创建一个服务器/客户端,使用sockets发送文本和其他媒体文件。 场景:-客户端以主机、端口和文件名为参数,将文件发送到服务器。 错误描述:-尝试执行下面的客户端代码时,文本文件“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()
三个月前把这个任务当作家庭作业。 解决这个问题的方法非常简单——您只需要读取文件,将读取的文本放入一个字符串变量并发送它。查看此服务器代码:
这是一种非常简单的方法。
客户机只需接收数据(作为文本)并将其保存在所需的位置。
为我工作的BMP,PNG和JPG图像也。
此时
file = ''
文件名无效。为了清楚起见,我还建议将file
重命名为filename
。相关问题 更多 >
编程相关推荐