zoukankan      html  css  js  c++  java
  • websocket实现群聊

    server
    
    
    
    # @File: 群聊
    from flask import Flask, render_template, request
    from geventwebsocket.handler import WebSocketHandler
    from gevent.pywsgi import WSGIServer
    from geventwebsocket.websocket import WebSocket
    
    app = Flask(__name__)
    user_socket_list = []
    
    
    @app.route('/ws')
    def ws():
        # 一个用户的长链接wsgi.websocket
        user_socket = request.environ.get("wsgi.websocket")  # type:WebSocket
        if user_socket:
            # 将每个链接存入列表中
            user_socket_list.append(user_socket)
        print(len(user_socket_list), user_socket_list)
        while 1:
            msg = user_socket.receive()
            print(msg)
            for usocket in user_socket_list:
                if user_socket == usocket:
                    continue
                try:
                    usocket.send(msg)
                except:
                    continue
    
    
    @app.route('/')
    def index():
        return render_template("many_person.html")
    
    
    if __name__ == '__main__':
        http_server = WSGIServer(("0.0.0.0", 7000), app, handler_class=WebSocketHandler)
        http_server.serve_forever()
    many_person.html


    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <p>发送内容:<input type="text" id="message"><button onclick="send_msg()">发送</button></p> <div id="msg_list" style=" 500px"> </div> </body> <script type="application/javascript"> var ws = new WebSocket("ws://192.168.12.41:7000/ws"); ws.onmessage = function (ws_status) { console.log(ws_status.data); var ptag = document.createElement("p"); ptag.innerText = ws_status.data; document.getElementById("msg_list").appendChild(ptag) }; function send_msg() { var msg = document.getElementById("message").value; var ptag = document.createElement("p"); ptag.style.cssText = "text-align: right"; ptag.innerText = msg; document.getElementById("msg_list").appendChild(ptag); ws.send(msg); } </script> </html>
  • 相关阅读:
    .net中AjaxPro的简单使用
    关于 Activity 中 startActivityForResult 和 onActivityResult
    产品经理值得读的12本书
    存储过程中使用事务与try catch
    扁平化数据解构转化成树形结构
    JavaScript编程精解
    泛型
    OATS:Orthogonal Array Testing Strategy
    等价类划分
    C# homework
  • 原文地址:https://www.cnblogs.com/xiao-xue-di/p/10157268.html
Copyright © 2011-2022 走看看