websocket实现简单的群聊

Posted zhao-peng-

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了websocket实现简单的群聊相关的知识,希望对你有一定的参考价值。

技术图片
 1 from flask import Flask, request, render_template
 2 
 3 from geventwebsocket.handler import WebSocketHandler
 4 from gevent.pywsgi import WSGIServer
 5 from geventwebsocket.websocket import WebSocket
 6 
 7 app = Flask(__name__)
 8 
 9 user_socket_list = []
10 
11 
12 @app.route(/conn_ws)
13 def ws_app():
14     # print(request.environ)
15 
16     user_socket = request.environ.get(wsgi.websocket)  # type: WebSocket
17     user_socket_list.append(user_socket)
18     print(len(user_socket_list), user_socket_list)
19     while True:
20         msg = user_socket.receive()
21         print(msg)
22         for i in user_socket_list:
23             i.send(msg)
24 
25 
26 @app.route(/index)
27 def index():
28     return render_template(my_qserv.html)
29 
30 
31 if __name__ == __main__:
32     http_serv = WSGIServer((0.0.0.0, 9527), app, handler_class=WebSocketHandler)
33 
34     http_serv.serve_forever()
后端
技术图片
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6 </head>
 7 <body>
 8 <input type="text" id="send_str">
 9 <button id="send_btn" onclick="send()">发送消息</button>
10 <p>
11 <div id="chat_list">
12 </div>
13 </p>
14 </body>
15 <script type="application/javascript">
16     var ws = new WebSocket(ws://192.168.11.67:9527/conn_ws);
17     ws.onmessage = function (messageEvent) {
18         console.log(messageEvent.data);
19         var ptag = document.createElement(p);
20         ptag.innerText = messageEvent.data;
21         document.getElementById(chat_list).appendChild(ptag);
22     };
23     function send() {
24         var send_str = document.getElementById(send_str).value;
25         ws.send(send_str);
26     }
27 </script>
28 </html>
前端

 

以上是关于websocket实现简单的群聊的主要内容,如果未能解决你的问题,请参考以下文章

Swoole实现基于WebSocket的群聊私聊

node进阶深入浅出websocket即时通讯-实现简易的群聊&私聊

使用SpringBoot开发群聊应用

4.基于NIO的群聊系统

WebSocket 实现群聊 - 简单测试例子

使用Nio实现一个简易的群聊和单聊