exer01 Message
# 1.定义Message消息类和cmd,content,sender,to四个属性,其中to默认为None
class Message:def __init__(self, cmd, content, sender, to=None):self.cmd = cmdself.content = contentself.sender = senderself.to = to
# 2. 创建登录消息对象msg1,聊天消息对象msg2
msg1 = Message('login', '小派', '小派')
msg2 = Message('chat', '出来踢球', '小派', '童童')
# 3. 输出msg1和msg2对象的__dict__属性
print(msg1.__dict__)
print(msg2.__dict__)
# 4. 先运行程序,然后解开下行注释,再运行程序查看结果
print(msg1.encode())
exer02 Json
# 1.定义Message消息类和cmd,content,sender,to四个属性,其中to默认为None
class Message:def __init__(self, cmd, content, sender, to=None):self.cmd = cmdself.content = contentself.sender = senderself.to = to
# 2. 创建登录消息对象msg1,聊天消息对象msg2
msg1 = Message('login', '小派', '小派')
msg2 = Message('chat', '出来踢球', '小派', '童童')
# 3. 输出msg1和msg2对象的__dict__属性
print(msg1.__dict__)
print(msg2.__dict__)
# 4. 先运行程序,然后解开下行注释,再运行程序查看结果
print(msg1.encode())
exer03 client
from socket import *
import jsonclass Message:def __init__(self, cmd, content, sender, to=None):self.cmd = cmdself.content = contentself.sender = senderself.to = toclass Client:def __init__(self, ip, port):self.socket = socket()self.socket.connect((ip, port))# 1. 定义sendMsg方法,将消息对象转换为json字符串发送def sendMsg(self, msg):msg = json.dumps(msg.__dict__)self.socket.send(msg.encode())def run(self):while True:content = input('请输入用户名:')if not content:continue# 2. 创建登录时消息对象msg = Message('login', content, content)# 3. 把下行代码修改为调用sendMsg发送消息self.sendMsg(msg)res = self.socket.recv(1024).decode()print('客户端收到的消息是:', res)self.socket.close()client = Client('l345.61it.cn', 10031)
client.run()