Fork me on GitHub

web-socket聊天室

准备工作:

1 安装gevent-websocket
pip3 install gevent-websocket

 

① 多人匿名聊天室:

from flask import Flask, request, render_template
from geventwebsocket.websocket import WebSocket
from geventwebsocket.websocket import WebSocketError
from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer
from flask import Flask, request,render_template
from geventwebsocket.websocket import WebSocket
from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer

app = Flask(__name__,template_folder='template')

# 首先我们程序进来之后访问index返回一个ws页面。
@app.route('/index')
def index():
    return render_template("ws.html")


user_socket_list = []


@app.route('/ws')
def ws():
    user_socket = request.environ.get('wsgi.websocket')
    print(request.environ)
    print(user_socket)
    if not user_socket:
        return "请使用WebSocket方式连接"
    user_socket_list.append(user_socket)
    print(user_socket_list)
    while True:
        user_msg = user_socket.receive()
        print(user_msg)
        for i in user_socket_list:
            if user_socket == i:       # 也就是自己给自己发,跳过。
                continue

            i.send(user_msg)
            # send_msg=input('input you word>>>>:')
            # user_socket.send(send_msg)


if __name__ == '__main__':
    http_serv = WSGIServer(('127.0.0.1', 9520), app, handler_class=WebSocketHandler)
    http_serv.serve_forever()
flask.py
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link href="https://cdn.bootcss.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>

<div class="col-md-6">
    <div class="panel panel-info" style="background-color: whitesmoke">
        <div class="panel-heading">
            <h3 class="panel-title">聊天室</h3>
        </div>
        <div class="panel-body" style="width: 500px;height: 400px;" id="chat_window">

        </div>
        <div style="margin-left: 400px;margin-bottom: 10px;">
            <input type="text" id="send_msg">
            <button id="btn_send">ENTER</button>
        </div>
    </div>
</div>


</body>
<script type="application/javascript">
    var ws = new WebSocket("ws://127.0.0.1:9520/ws");
    //创建一个新的websocket连接。
    //    ws.onopen=function () {
    //        ws.send('你好')
    //    };

    //使用ws实例出的ws监听onmessage事件。
    ws.onmessage = function (serv_msg) {
        create_chat("y", serv_msg.data);
//        console.log(serv_msg);
//        console.log(serv_msg.data)
    };
    //创建对话内容
    function create_chat(self, content) {
        //self和content
        if (self == "w") {
            //如果为自己那么放到右边,创建
            self = "right";
            var spantag = document.createElement("span");
            spantag.innerText = content;
            var spantag1 = document.createElement("span");
            spantag1.innerText = ":我";
        } else {
            self = "left";
            var spantag = document.createElement('span');
            spantag.innerText = "你:";
            var spantag1 = document.createElement('span');
            spantag1.innerText = content;
        }
        var divtag = document.createElement("div");
        divtag.style = "text-align:" + self;
        divtag.appendChild(spantag);
        divtag.appendChild(spantag1);
        var chat_window = document.getElementById("chat_window");
        chat_window.appendChild(divtag);
    }
    document.getElementById("btn_send").addEventListener("click", function () {
        //addEventListener对点击事件click进行监听
        var send_msg = document.getElementById("send_msg");
        ws.send(send_msg.value);
        //拿到发送的内容
        create_chat("w", send_msg.value);
        //发送之后将输入框清空
        send_msg.value = "";
    })

</script>
</html>
html

 

② 多人实名聊天室:

from flask import Flask, request, render_template
from geventwebsocket.websocket import WebSocket
from geventwebsocket.websocket import WebSocketError
from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer

import json

app = Flask(__name__,template_folder='template')


@app.route("/index")
def index():
    return render_template("group_chat.html")


user_socket_list = []
user_socket_dict = {}


@app.route("/ws/<username>")
def ws(username):
    user_socket = request.environ.get("wsgi.websocket")  # type:WebSocket
    if not user_socket:
        return "请使用WebSocket方式连接"
    user_socket_dict[username] = user_socket
    print(user_socket_dict)
    while True:
        try:
            user_msg = user_socket.receive()
            for user_name, u_socket in user_socket_dict.items():
                who_send_msg = {
                    "send_user": username,
                    "send_msg": user_msg
                }
                if user_socket == u_socket:
                    continue
                u_socket.send(json.dumps(who_send_msg))
        except WebSocketError as e:
            user_socket_dict.pop(username)
            print(user_socket_dict)
            print(e)


if __name__ == '__main__':
    # app.run("0.0.0.0",9527,debug=True)
    http_serv = WSGIServer(("127.0.0.3", 9522), app, handler_class=WebSocketHandler)
    http_serv.serve_forever()
group_chat.py
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link href="https://cdn.bootcss.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>

<div class="col-md-6">
    <div class="panel panel-info" style="background-color: whitesmoke">
        <div class="panel-heading">
            <h3 class="panel-title">聊天室</h3>
            你是谁:<input type="text" id="username">
            <button id="create_ws" onclick="go_to()">创建ws连接</button>
        </div>
        <div class="panel-body" style="width: 500px;height: 400px;" id="chat_window">

        </div>
        <div style="margin-left: 400px;margin-bottom: 10px;">
            <input type="text" id="send_msg">
            <button id="btn_send">ENTER</button>
        </div>
    </div>
</div>

</body>
<script type="application/javascript">
    var ws_url = "ws://127.0.0.3:9522/ws/";
    var ws = null;
    function go_to() {
        var username = document.getElementById("username");
        ws = new WebSocket(ws_url + username.value);

        ws.onmessage = function (serv_msg) {
            msg = JSON.parse(serv_msg.data);
            create_chat("y", msg)
        };
    }
    function create_chat(self, content) {
        if (self == 'w') {
            self = "right";
            var spantag = document.createElement("span");
            spantag.innerText = content.send_msg;
            var spantag1 = document.createElement("span");
            spantag1.innerText = ":我";
        } else {
            self = 'left';
            var spantag = document.createElement("span");
            spantag.innerText = content.send_user + ":";
            var spantag1 = document.createElement("span");
            spantag1.innerText = content.send_msg;
        }
        var divtag = document.createElement("div");
        divtag.style = "text-align:" + self;

        divtag.appendChild(spantag1);
        divtag.appendChild(spantag);
        var chat_window = document.getElementById("chat_window");
        chat_window.appendChild(divtag);
    }
    document.getElementById("btn_send").addEventListener("click", function () {
        var send_msg = document.getElementById("send_msg");
        ws.send(send_msg.value);
        var s_msg = {send_msg: send_msg.value};
        create_chat("w", s_msg);
        send_msg.value = "";
    })
</script>


</html>
html

 

③ 私人聊天室;

from flask import Flask, request, render_template
from geventwebsocket.websocket import WebSocket
from geventwebsocket.websocket import WebSocketError
from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer

import json

app = Flask(__name__,template_folder='template')


@app.route("/index")
def index():
    return render_template("pri_chat.html")

user_socket_list = []
user_socket_dict = {}


@app.route("/ws/<username>")
def ws(username):
    user_socket = request.environ.get("wsgi.websocket")  # type:WebSocket
    if not user_socket:
        return "请使用WebSocket方式连接"
    user_socket_dict[username] = user_socket
    print(user_socket_dict)
    while True:
        try:
            user_msg = user_socket.receive()
            user_msg=json.loads(user_msg)
            to_user_socket=user_socket_dict.get(user_msg.get("to_user"))
            send_msg={
                "send_msg":user_msg.get("send_msg"),
                "send_user":username
            }
            to_user_socket.send(json.dumps(send_msg))
            # for user_name, u_socket in user_socket_dict.items():
            #     who_send_msg = {
            #         "send_user": username,
            #         "send_msg": user_msg
            #     }
            #     if user_socket == u_socket:
            #         continue
            #     u_socket.send(json.dumps(who_send_msg))
        except WebSocketError as e:
            user_socket_dict.pop(username)
            print(user_socket_dict)
            print(e)


if __name__ == '__main__':
    # app.run("0.0.0.0",9527,debug=True)
    http_serv = WSGIServer(("127.0.0.2", 9521), app, handler_class=WebSocketHandler)
    http_serv.serve_forever()
privte_chat.py
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link href="https://cdn.bootcss.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>

<div class="col-md-6">
    <div class="panel panel-info" style="background-color: whitesmoke">
        <div class="panel-heading">
            <h3 class="panel-title">聊天室</h3>
            你是谁:<input type="text" id="username">
            给谁发:<input type="text" id="to_user">
            <button id="create_ws" onclick="go_to()">创建ws连接</button>
        </div>
        <div class="panel-body" style="width: 500px;height: 400px;" id="chat_window">
        </div>
        <div style="margin-left: 400px; margin-bottom: 10px;">
            <input type="text" id="send_msg">
            <button id="btn_send">ENTER</button>
        </div>
    </div>
</div>


</body>
<script type="application/javascript">
    var ws_url = "ws://127.0.0.1:9527/ws/";
    var ws = null;
    function go_to() {
        var username = document.getElementById("username");
        ws = new WebSocket(ws_url + username.value);

        ws.onmessage = function (serv_msg) {
            msg = JSON.parse(serv_msg.data);
            create_chat("y", msg)
        };
    }
    function create_chat(self, content) {
        if (self == 'w') {
            self = "right";
            var spantag = document.createElement("span");
            spantag.innerText = content.send_msg;
            var spantag1 = document.createElement("span");
            spantag1.innerText = ":我";
        } else {
            self = 'left';
            var spantag = document.createElement("span");
            spantag.innerText = content.send_user + ":";
            var spantag1 = document.createElement("span");
            spantag1.innerText = content.send_msg;
        }
        var divtag = document.createElement("div");
        divtag.style = "text-align:" + self;

        divtag.appendChild(spantag1);
        divtag.appendChild(spantag);
        var chat_window = document.getElementById("chat_window");
        chat_window.appendChild(divtag);
    }
    document.getElementById("btn_send").addEventListener("click", function () {
        var send_msg = document.getElementById("send_msg");
        var to_user = document.getElementById("to_user");
        send_msg_json = {
            send_msg: send_msg.value,
            to_user: to_user.value
        };
        ws.send(JSON.stringify(send_msg_json));
        var s_msg = {send_msg: send_msg.value};
        create_chat("w", s_msg);
        send_msg.value = "";
    })
</script>

</html>
html

 

posted @ 2018-08-22 08:31  道阻切长  阅读(106)  评论(0编辑  收藏  举报