前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >day119-Flask的websocket使用

day119-Flask的websocket使用

原创
作者头像
少年包青菜
修改2020-04-26 10:15:50
6410
修改2020-04-26 10:15:50
举报
文章被收录于专栏:Python 学习Python 学习

# 着重注意前段 websocket 实例的函数内作用域问题

1.websocket之群聊

1.1后端代码

代码语言:javascript
复制
import json
from pprint import pprint

from flask import Flask, request
from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer
from geventwebsocket.websocket import WebSocket  # 做语法提示使用

app = Flask(__name__)

# websocket 的列表
user_socket_dict = {}


@app.route('/my_ws/<nick_name>')
def ws(nick_name):
    print(nick_name + '连接服务器')
    # 记录客户端信息
    user_socket = request.environ.get('wsgi.websocket')  # type: WebSocket

    if nick_name not in user_socket_dict:
        user_socket_dict[nick_name] = user_socket
    while 1:
        # 收消息
        msg = user_socket.receive()
        for socket in user_socket_dict.values():
            # 给每一个 socket 对象 send 消息
            socket.send('来自用户{}-->{}'.format(nick_name, msg))


if __name__ == '__main__':
    # 跟实际的 app 的原型方式不一样
    print('服务启动')
    http_service = WSGIServer(('127.0.0.1', 5000), app, handler_class=WebSocketHandler)
    http_service.serve_forever()

1.2前段代码

代码语言:javascript
复制
<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Title</title>
</head>
<body>
<h1>websocket群聊实例</h1>
<hr id="hello">
<hr>
<p>
    我的昵称: <input type="text" id="nickName">
    <button id="connect">连接服务器</button>
</p>
<p>
    编辑内容: <input type="text" id="chatContent">
    <button id="submitContent">点击提交</button>
</p>
</body>
<script>
    // 建立连接
    document.getElementById('connect').onclick = function () {
        let nickName = document.getElementById('nickName').value
        // 定义全局新连接
        ws = new WebSocket('ws://127.0.0.1:5000/my_ws/' + nickName)

        // 注意 ws 的作用域,在建立连接之后监听
        ws.onmessage = function (data) {
            // 监听获取后端的 send,组装进代码块
            let msg = data.data
            let htmlBlock = document.createElement("p")
            htmlBlock.innerText = msg
            document.getElementById('hello').appendChild(htmlBlock)
        }
    }

    // 提交内容
    document.getElementById('submitContent').onclick = function () {
        let content = document.getElementById('chatContent').value
        console.log(content)
        // 提交内容
        // 此时的 ws 已经被建立,所有可以全局函数内使用
        ws.send(content)
    }

</script>
</html>

2.websocket之指定好友聊天

2.1后端代码

代码语言:javascript
复制
import json
from pprint import pprint

from flask import Flask, request
from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer
from geventwebsocket.websocket import WebSocket  # 做语法提示使用

app = Flask(__name__)

# websocket 的列表
user_socket_dict = {}


@app.route('/my_ws/<nick_name>')
def ws(nick_name):
    # print(name + '连接服务器')
    # 记录客户端信息
    user_socket = request.environ.get('wsgi.websocket')  # type: WebSocket

    if nick_name not in user_socket_dict:
        user_socket_dict[nick_name] = user_socket
    print(user_socket_dict)
    while 1:
        # 收消息
        # 反序列化字符串
        msg = json.loads(user_socket.receive())
        # 取到好友名字传递信息
        friend = msg['friend_name']
        content = msg['content']
        send_content = '来自用户{}-->{}'.format(nick_name, content)
        # 给好友发一份
        user_socket_dict[friend].send(send_content)
        # 给自己也发一份
        user_socket.send(send_content)


if __name__ == '__main__':
    # 跟实际的 app 的原型方式不一样
    print('服务启动')
    http_service = WSGIServer(('127.0.0.1', 5000), app, handler_class=WebSocketHandler)
    http_service.serve_forever()

2.2前端代码

代码语言:javascript
复制
<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Title</title>
</head>
<body>
<h1>websocket一对一实例</h1>
<hr id="hello">
<hr>
<p>
    我的昵称: <input type="text" id="nickName">
    <button id="connect">连接服务器</button>
</p>
<p>
    发给好友: <input type="text" id="friendName">
</p>
<p>
    编辑内容: <input type="text" id="chatContent">
    <button id="submitContent">点击提交</button>
</p>
</body>
<script>
    // 建立连接
    document.getElementById('connect').onclick = function () {
        let name = document.getElementById('nickName').value
        // 定义全局新连接
        ws = new WebSocket('ws://127.0.0.1:5000/my_ws/' + name)

        // 定义完连接直接监听后端数据
        ws.onmessage = function (data) {
            // 监听获取后端的 send,组装进代码块
            let msg = data.data
            let htmlBlock = document.createElement("p")
            console.log('后端 msg', msg)
            htmlBlock.innerText = msg
            document.getElementById('hello').appendChild(htmlBlock)
        }

        // 提交聊天数据
        document.getElementById('submitContent').onclick = function () {
            // 获取想要提交的好友
            let friendName = document.getElementById('friendName').value
            // 获取编辑的内容
            let content = document.getElementById('chatContent').value

            let postMsg = {'friend_name': friendName, 'content': content}
            // 提交内容
            // 此时的 ws 已经被建立,所有可以全局函数内使用
            ws.send(JSON.stringify(postMsg))
            console.log(JSON.stringify(postMsg))
        }
    }

</script>
</html>

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1.websocket之群聊
    • 1.1后端代码
      • 1.2前段代码
      • 2.websocket之指定好友聊天
        • 2.1后端代码
          • 2.2前端代码
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档