Helloworld
其它内容参考 Java 开发(接口与包都一样)。只是函数命名风格上,由“驼峰”转成了“蛇形”
- for Client
async def main():
#打开客户端会话,并监听(用 url 形式打开)
session = await (SocketD.create_client("sd:ws://127.0.0.1:8602/?token=1b0VsGusEkddgr3d")
.open())
entity = StringEntity("Hello wrold!").meta_put("sender","noear")
#发送
session.send("/demo", entity)
#发送并请求(且,等待一个答复)
session.send_and_request("/demo", entity).then_reply(lambda reply:
#打印
log.info(reply.data_as_string())
)
#发送并订阅(且,接收零个或多个答复流)
session.send_and_subscribe("/demo", entity).then_reply(lambda reply:
#打印
log.info(reply.data_as_string()) or (reply.is_end() and log.info("the end!"))
)
- for Server (lambda style)
async def main():
await (SocketD.create_server("sd:ws")
.listen(EventListener()
.do_on_open(lambda s:
#会话打开时
log.info(s.session_id())
).do_on_message(lambda s, m:
#收到任意消息时(方便做统一的日志打印)
log.info(str(m))
).do_on("/demo", lambda s, m:
#收到"/demo"事件的消息时
(m.is_request() or m.is_subscribe()) and s.reply_end(m, StringEntity("And you too."))
)).start())
await asyncio.Future()
if __name__ == "__main__":
asyncio.run(main())
- for Server (classic style)
class DemoListener(Listener):
async def on_open(self, s: Session):
# 会话打开时
log.info(s.session_id())
pass
async def on_message(self, s: Session, m: Message):
# 收到任意消息时(方便做统一的日志打印)
log.info(m.data_as_string())
if m.event() == "/demo":
# 收到"/demo"事件的消息时。如果是请求或订阅?则进行签复
if m.is_request() or m.is_subscribe():
await s.reply_end(m, StringEntity("And you too."))
async def on_close(self, s: Session):
log.info(s.session_id())
pass
async def on_error(self, s: Session, error):
log.info(s.session_id())
log.info(error)
pass
async def main():
server = await (SocketD.create_server("sd:ws")
.listen(DemoListener()).start())
await asyncio.Future()
if __name__ == "__main__":
asyncio.run(main())