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实现简单的群聊的主要内容,如果未能解决你的问题,请参考以下文章