我正在进行Python培训。但是,我使用的视频使用Python2进行训练。我正在使用Python3,所以我试图将Python2练习转换为Python3。
我已经解决了不同的错误,但是对于这个错误“需要像对象一样的字节,而不是builtin_function_or_method”我无法找到解决方案
我一直在'connection.send(self.data)'行的server.py上得到错误(见图片)。我相信我需要将self.data转换为字节,因为.send需要字节,但我不知道该怎么做。我尝试过在不同领域进行编码,但没有成功。我相信我需要对“connection.send(self.data)”进行编码,但我不知道如何编码。有谁知道我错过了什么?
Client.py 导入套接字
class datasave:
def __init__(self, name = '',data = ''):
self.name = name
self.data = data
return
def load(self, connection):
print("Self Data ",self.data)
connection.send(self.data)
connection.close()
return
import socket
PORT = 50002
files = {
"File1" : "The quick brown fox jumped over the lazy dogs" ,
"File2" : "If a woodchuck could chuck wood" ,
"File3" : "Now you're just showing off" ,
}
for i in files:
s = socket.socket(socket.AF_INET , socket.SOCK_STREAM)
s.connect(('127.0.0.1', PORT))
s.send("SAVE".encode())
s.send(i.encode())
s.send(files[i].encode())
print("check")
s.close()
for i in files:
s = socket.socket(socket.AF_INET , socket.SOCK_STREAM)
s.connect(('127.0.0.1', PORT))
s.send("LOAD".encode())
s.send(i.encode())
print("check 2")
data = s.recv(4096).decode()
if data != files[i]:
print("Failed: %s != %s" % (data , files[i]))
s.close()
s = socket.socket(socket.AF_INET , socket.SOCK_STREAM)
s.connect(('127.0.0.1', PORT))
s.send("LOAD".encode())
s.send("File4".encode())
data = s.recv(4096).decode()
if data != "File Not Found":
print("Error check failed")
else:
print("SUCCESS!")
s.close()
server.py
class datasave:
def __init__(self, name = '',data = ''):
print("Save")
self.name = name
self.data = data
return
def load(self, connection):
print("LOAD Funciton")
print("%s:\t%s" % (self.name, self.data))
connection.send(self.data)
connection.close()
return
def main():
HOST='127.0.0.1'
PORT = 50002
sentinel = False
found_file = False
opts_list = ["SAVE","LOAD"]
obj_list = []
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(10)
while(sentinel != True):
connection, address = s.accept()
mode = connection.recv(4096).decode()
if mode == opts_list[0]:
obj = datasave(connection.recv(4096), connection.recv(4096))
connection.close()
obj_list.append(obj)
elif mode == opts_list[1]:
name = connection.recv(4096).decode()
for obj in obj_list:
if obj.name == name:
obj.load(connection)
found_file = True
if found_file == False:
connection.send("File Not Found").encode()
else:
found_file == False
else:
print(mode)
sentinel = True
main()的