基于flask框架,使用websocket实现多人聊天室功能

后端代码:

 

# web_socket 的收发机制
# web_socket  -->  web + socket  -->  http协议 + socket
# web_socket协议就是ws协议
# 基于flask框架为web_socket提供服务
from flask import Flask,request,render_template
from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer

from geventwebsocket.websocket import WebSocket  # 做语法提示用的

app = Flask(__name__)  # type: Flask


user_socket_list = []

@app.route("/ws")
def web_sck():
    # print(request.environ)  #  打印的原始请求数据
    # 这个东西其实就是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()  # 接收客户端传入数据
        # 在浏览器中content的中输入ws ,readyState如果为1 表示连接成功,如果等于3表示,连接成功后又断开了连接,0 表示没有开启
        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("web_sck1.html")


if __name__ == "__main__":
    # app.run("0.0.0.0",8000,debug=True)
    http_serve = WSGIServer(("0.0.0.0",8000),app,handler_class=WebSocketHandler)
    http_serve.serve_forever()  # 启动这个web-server请求

 

 

前端代码:

 

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>多人聊天</title>
</head>
<body>
<p>
    发送内容:
    <input type="text" id="message">
    <button onclick="send_msg()">点击发送</button>
</p>
<div id="msg_list" style="width: 500px">

</div>



<script type="application/javascript">
    var ws = new WebSocket("ws://192.168.12.38:8000/ws") ; // 指定发送的链接地址
    ws.onopen = function(){  //
        {#ws.send("hello")#}
    };
    // 前端接收消息   ws_info 接收数据的容器
    ws.onmessage = function (ws_info) {
        console.log(ws_info.data);  //后端返回的响应数据,存放在ws_info下的data中
        var ptag = document.createElement("p");  //创建一个p标签
        ptag.innerText = ws_info.data;//将data中的数据存放标签中
        document.getElementById("msg_list").appendChild(ptag)
    };
    
    function send_msg() {
        var msg = document.getElementById("message").value;
        var ptag = document.createElement("p");  //创建一个p标签
        ptag.style.cssText = "text-align: right;";
        ptag.innerText = msg;//将data中的数据存放标签中
        document.getElementById("msg_list").appendChild(ptag)
        ws.send(msg);  // 拿到前端输入的内容,向后端发送
    }
</script>
</body>
</html>

 

posted @ 2018-12-21 17:44  熊猫大侠-呀呀呀!!!  阅读(414)  评论(0编辑  收藏  举报