我写了一个客户端和一个服务器程序,客户端将文件发送到服务器,服务器打印文件的内容。这是代码段:
Server---------------->serverprog.py
import socket
from threading import *
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.gate.bind(("127.0.0.1", self.port))
self.listen()
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)
a = Server(8888)
Client ------------------>clientprog.py
import socket
from threading import *
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('127.0.0.1', 8888, 'datasend.txt')
如果我同时编译客户端和服务器,它会给我以下服务器程序错误:
Traceback (most recent call last):
File "receivefilepg.py", line 25, in <module>
a = Server(8888)
File "receivefilepg.py", line 15, in __init__
self.listen()
File "receivefilepg.py", line 20, in listen
self.receiveFilename(conn)
AttributeError: Server instance has no attribute 'receiveFilename'
我在这里做错了什么?任何建议都会有所帮助!
答案 0 :(得分:2)
错误告诉您所有需要知道的内容,您在server.listen
方法中输入了拼写错误,而不是调用self.receiveFileName
来调用self.receiveFilename
。