我一直在尝试实现一个小型的SERVER - CLIENT应用程序但是跑进了errrr:
socket.error:[Errno 10057]发送或接收数据的请求是 因为套接字没有连接而且(当发送时没有连接) 使用sendto调用的数据报套接字没有提供地址
服务器:
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')
答案 0 :(得分:7)
服务器有一个服务器套接字,用于accept
传入连接,另一个套接字用于每个连接。从你的代码:
self.gate.listen(10)
while True:
add = self.gate.accept()
self.reciveFileName() # which calls self.gate.recv()
而不是在reciveFilename
和reciveFile
中运行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
目前正在侦听套接字。相反,您必须设计一个适当的协议,指定文件名何时结束并开始文件内容。例如,您可以让文件名以b'\0'
结尾,并让服务器搜索该字节。