websocket之简易聊天室

Posted 燃烧着

tags:

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

一,带昵称的群聊

#!/usr/bin/env python
# -*- coding:utf8 -*-

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


app = Flask(__name__)
user_socket_dict = {}


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


@app.route("/ws/<nick_name>")  # ws://127.0.0.1:8000/ws
def ws(nick_name):
    # print(request.environ)
    # print(request.environ.get("wsgi.websocket"))
    # 链接 <geventwebsocket.websocket.WebSocket object at 0x000001A7380D0C78>
    user_socket = request.environ.get("wsgi.websocket")  # type:WebSocket # 写上这个,代码可以有提示
    if user_socket:
        user_socket_dict[nick_name] = user_socket
    else:
        return render_template("index.html", msg="请使用web_socket链接")
    while 1:
        msg = user_socket.receive()
        for user_name, u_socket in user_socket_dict.items():  # type:WebSocket
            if user_socket != u_socket:  # 不给自己发消息
                try:
                    u_socket.send(json.dumps({"nick_name": nick_name, "msg": msg}))  # 发送人是
                except Exception as e:
                    continue


if __name__ == __main__:
    http_server = WSGIServer(("127.0.0.1", 8000), app, handler_class=WebSocketHandler)
    # 使用WSGIServer,而不是flask自带的werkzeug,处理, 如果本次请求是ws开头的,就交给WebSocketHandler
    # 处理数据(给environ中添加websocket相关的键值对),处理完之后交给app
    http_server.serve_forever()
    # app.run()

templates:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{{ msg }}
<h1>群P开始了</h1>
输入你的昵称:<input type="text" id="nick_name">
<button onclick="createWebsocket()">链接群聊</button>

编辑消息:<input type="text" id="msg_s">
<button onclick="send_msg()">发送</button>
<div style="border: 2px solid; width: 500px;height: 800px;" id="text_div">

</div>

<script>
    var ws = "";
    var text_div = document.getElementById("text_div");
    var nickName = "";
    function createWebsocket() {
        let nick_name = document.getElementById("nick_name").value;
        nickName = nick_name;
        let w_s = new WebSocket("ws://127.0.0.1:8000/ws/" + nickName);  // 把名称当作url参数发过去
        ws = w_s;
        console.log("ws://127.0.0.1:8000/ws/" + nickName);
        ws.onmessage = function (data) {
            var obj_data = JSON.parse(data.data);
            console.log(data.data);
            var p_ele = <p>+ obj_data.nick_name + :+ obj_data.msg +</p>;
            text_div.innerHTML += p_ele
    }}

    function send_msg() {
        var msg_s = document.getElementById("msg_s").value;
        let p_ele_s = "<p style=‘text-align: right‘>" + msg_s + : + nickName + "</p>";
        text_div.innerHTML += p_ele_s;
        ws.send(msg_s);
    }
</script>
</body>
</html>

二,带昵称的单聊

#!/usr/bin/env python
# -*- coding:utf8 -*-

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


app = Flask(__name__)
user_socket_dict = {}


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


@app.route("/ws/<nick_name>")  # ws://127.0.0.1:8000/ws
def ws(nick_name):
    # print(request.environ)
    # print(request.environ.get("wsgi.websocket"))
    # 链接 <geventwebsocket.websocket.WebSocket object at 0x000001A7380D0C78>
    user_socket = request.environ.get("wsgi.websocket")  # type:WebSocket # 写上这个,代码可以有提示
    if user_socket:
        user_socket_dict[nick_name] = user_socket
    else:
        return render_template("index.html", msg="请使用web_socket链接")
    while 1:
        msg = user_socket.receive()
        msg_dict = json.loads(msg)
        to_user = msg_dict.get(to_user)
        msg = msg_dict.get("msg")
        to_user_socket = user_socket_dict.get(to_user)  # type:WebSocket
        to_user_socket.send(json.dumps({"nick_name": nick_name, "msg": msg}))


if __name__ == __main__:
    http_server = WSGIServer(("127.0.0.1", 8000), app, handler_class=WebSocketHandler)
    # 使用WSGIServer,而不是flask自带的werkzeug,处理, 如果本次请求是ws开头的,就交给WebSocketHandler
    # 处理数据(给environ中添加websocket相关的键值对),处理完之后交给app
    http_server.serve_forever()
    # app.run()

templates:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{{ msg }}
<h1>群P开始了</h1>
输入你的昵称:<input type="text" id="nick_name">
<button onclick="createWebsocket()">链接群聊</button>

<p>与:<input type="text" id="to_user">轻声细语</p>

编辑消息:<input type="text" id="msg_s">
<button onclick="send_msg()">发送</button>
<div style="border: 2px solid; width: 500px;height: 800px;" id="text_div">

</div>

<script>
    var ws = "";
    var text_div = document.getElementById("text_div");
    var nickName = "";
    function createWebsocket() {
        let nick_name = document.getElementById("nick_name").value;
        nickName = nick_name;
        let w_s = new WebSocket("ws://127.0.0.1:8000/ws/" + nickName);  // 把名称当作url参数发过去
        ws = w_s;
        console.log("ws://127.0.0.1:8000/ws/" + nickName);
        ws.onmessage = function (data) {
            var obj_data = JSON.parse(data.data);
            console.log(data.data);
            var p_ele = <p>+ obj_data.nick_name + :+ obj_data.msg +</p>;
            text_div.innerHTML += p_ele
    }}

    function send_msg() {
        var msg_s = document.getElementById("msg_s").value;
        var to_user = document.getElementById("to_user").value;
        let p_ele_s = "<p style=‘text-align: right‘>" + msg_s + : + nickName + "</p>";
        text_div.innerHTML += p_ele_s;
        var msg_obj = JSON.stringify({to_user:to_user,msg:msg_s});
        ws.send(msg_obj);
    }
</script>
</body>
</html>

 


以上是关于websocket之简易聊天室的主要内容,如果未能解决你的问题,请参考以下文章

websocket搭建简易的聊天室--勿喷

swoole用WebSocket服务器搭建一个简易的聊天室功能

swoole用WebSocket服务器搭建一个简易的聊天室功能

vue使用WebSocket模拟实现聊天功能-简易版

php+websocket搭建简易聊天室实践

Laravel + Swoole 打造IM简易聊天室