我既有服务器又有客户端,我正尝试通过套接字从客户端到服务器发送一个类对象,该类对象在服务器I中包含一个具有2个用户名的列表和一个具有列表2长度的变量。可以成功访问给我2个的ctotalusers,但是userslist给我[]为什么用户不见了?
客户
import socket, pickle, json
def create_send_users(i, y, k):
msg = {'i': i, 'users': y, 'k': k}
return json.dumps(msg)
class CaUsers(object):
ctotalusers = None
userslist = []
users = CaUsers()
users.userslist.append("bob")
users.userslist.append("alice")
users.ctotalusers = len(users.userslist)
a_users = pickle.dumps(users)
msg = create_send_users("i", a_users, "k")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 7038))
s.send(msg)
服务器
import socket, pickle, json, sys
class CaUsers(object):
ctotalusers = None
userslist = []
HOST = '127.0.0.1'
PORT = 7038
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('# Socket created')
# Create socket on port
try:
s.bind((HOST, PORT))
except socket.error as msg:
print('# Bind failed. ')
sys.exit()
print('# Socket bind complete')
# Start listening on socket
s.listen(10)
print('# Socket now listening')
# Wait for client
conn, addr = s.accept()
print('# Connected to ' + addr[0] + ':' + str(addr[1]))
# Receive data from client
while True:
data = conn.recv(4096)
if data:
users = pickle.loads(json.loads(data)["users"])
print users.ctotalusers # correct gives me 2
print users.userslist # wrong gives me []
s.close()