gpt4 book ai didi

Python - 通过套接字发送文件

转载 作者:太空宇宙 更新时间:2023-11-03 13:22:32 25 4
gpt4 key购买 nike

我一直在尝试实现一个小型 SERVER - CLIENT 应用程序,但遇到了错误:

socket.error: [Errno 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied

服务器:

class Server:
gate = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
port = 0
file = ''

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:
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()



a = Server(1111)

客户:

class Client:
gateway = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#host = socket.gethostname()
host = ''
port = 0
file = ''

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()
self.sendFile()

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()



a = Client('93.103.56.251', 1111, 'data.txt')

最佳答案

服务器有一个用于接受传入连接的服务器套接字,以及用于每个这些连接的另一个套接字。从您的代码:

self.gate.listen(10)
while True:
add = self.gate.accept()
self.reciveFileName() # which calls self.gate.recv()

不要在 reciveFilenamereciveFile 中对 self.gate 进行操作(顺便说一句,正确的拼写是 receive),你应该使这些方法在 accepted 上运行连接,像这样:

def listen(self):
self.gate.listen(10)
while True:
conn,address = self.gate.accept()
self.receiveFilename(conn)

def receiveFilename(self, sock):
buf = sock.recv(1024)
print('First bytes I got: ' + buf)

此外,reciveFilename 当前永远在套接字上监听。相反,您必须设计一个适当的协议(protocol)来指定文件名何时结束以及文件内容何时开始。例如,您可以让文件名以 b'\0' 结尾,让服务器搜索该字节。

关于Python - 通过套接字发送文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9385509/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com