与小组实时交谈

nejma的Python项目详细描述


奈杰玛

nejma允许您管理多个实时连接并向组或用户发送消息多个选项卡…

看看这个例子nejma-chat,一个使用nejmastarlette构建的简单聊天应用程序。

安装

$ pip install nejma

开始

下面是一个对websockets使用nejma的示例。

首先从NEJMA导入通道和通道层

fromnejmaimportChannel,channel_layer

在“连接”上创建频道

asyncdefon_connect(self,websocket,**kwargs):awaitsuper().on_connect(websocket,**kwargs)self.channel=Channel(send=websocket.send)

添加组、频道或发送消息

asyncdefon_receive(self,websocket,data):# Adds a channel to a giving groupself.channel_layer.add(group,self.channel)# Removes a channel from a given groupself.channel_layer.remove(group,self.channel)# Removes a channel from all the groupsself.channel_layer.remove_channel(self.channel)# Reset all the groupsself.channel_layer.flush()awaitself.channel_layer.group_send(group,"Welcome !")

最后,在连接关闭后卸下通道

asyncdefon_disconnect(self,websocket,close_code):self.channel_layer.remove_channel(self.channel)

星体


要将nejmastarlette一起使用,只需从nejma导入websocketendpoint

fromchannels.ext.starletteimportWebSocketEndpoint@app.websocket_route("/ws")classChat(WebSocketEndpoint):encoding="json"asyncdefon_receive(self,websocket,data):room_id=data['room_id']message=data['message']username=data['username']ifmessage.strip():group=f"group_{room_id}"self.channel_layer.add(group,self.channel)payload={"username":username,"message":message,"room_id":room_id}awaitself.channel_layer.group_send(group,payload)

文档

nejma提供的ChannelLayer类公开以下方法:

add(group, channel)

向给定组添加频道。

self.channel_layer.add(group,self.channel)

remove(group, channel) 从给定组中删除频道

self.channel_layer.remove(group,self.channel)

remove_channel(channel) 从所有组中删除频道

self.channel_layer.remove_channel(self.channel)

flush() 重置所有组

self.channel_layer.flush()

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
ByteArrayOutputStream的java解码属性   java S3 SDK在上载时更新单个对象,而不是创建新文件   java hibernate:无法从eclipse连接到DB   java如何在强制转换JComboBox之前检查其类型?   http从Java中的GETPOST请求方法捕获URI、资源名称,如开发人员工具中所示   java在Spring@Bean方法中返回接口的局限性   Java中的Web服务和客户端(使用Eclipse Apache Axis 2自底向上服务)某些代码会引发异常   java spring安全+rest不起作用   java将LinkedList添加到包含LinkedList的LinkedList并更改添加的LinkedList   java是否临时删除对象的属性?   java使用AnimatedGifEncoder类创建的gif图像的部分帧是不透明的   java如何高效地处理maven3时间戳快照?   java向集合对象添加另一项   java如何将动态参数传递给jquery函数   java使用libGdx桌面端口作为Android GLES20的仿真器