欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 创投人物 > L3-21

L3-21

2025/4/6 13:27:49 来源:https://blog.csdn.net/m0_46727639/article/details/147013359  浏览:    关键词:L3-21

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()

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词