websocket 二合一

server

from flask import Flask, request, render_template
from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer
from geventwebsocket.websocket import WebSocket
import json
app = Flask(__name__)

user_socket_dict = {}  # 字典

@app.route('/conn_ws/<user_nick>')  #http 协议,
def ws_app(user_nick):

    user_socket = request.environ.get('wsgi.websocket')  #type:WebSocket
    user_socket_dict[user_nick] = user_socket  # { 昵称:user信息 }
    print(len(user_socket_dict), list(user_socket_dict.keys()))

    while True:    # user_socket 是一个内存地址
        msg =  user_socket.receive()  #  hang 住了
        msg_dict = json.loads(msg)

        to_user = msg_dict.get('to_user')
        if to_user == 'all':
            for ss in list(user_socket_dict.values()):
                ss.send(msg)

        else:

            to_user_socket =  user_socket_dict.get(to_user)
            to_user_socket.send(msg)

@app.route('/')
def index():
    return render_template('my_ws.html')

if __name__ == '__main__':
    # app.run()
    http_ser = WSGIServer(('0.0.0.0',9009),app,handler_class=WebSocketHandler)  # 应用程序网关接口
    http_ser.serve_forever()

页面 html  

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>单聊</title>
</head>
<body>
<p><input type="text" id="nick">
    <button onclick="login()">登陆聊天室</button>
</p>

发送给: <input type="text" id="to_user" placeholder="找谁聊?"> 消息: <input type="text" id="send_str">

<button id="sin_btn" onclick="sin_send()">发消息</button>
<button id="send_btn" onclick="send()">群聊发消息</button>

<p>
<div id="chat_list">
</div>
</p>

</body>
<script type="text/javascript">
    var ws = null;  //公共变量,

    function login() {
        var nick = document.getElementById('nick').value;
        ws = new WebSocket('ws://192.168.11.94:9009/conn_ws/' + nick); //登录时候创建连接
        ws.onmessage = function (messageEvent) {                           //等待消息
            console.log(messageEvent.data);
            var ptag = document.createElement('p');
            var message = JSON.parse(messageEvent.data);

            ptag.innerText = message.from_user + ' : ' + message.message;
            document.getElementById('chat_list').appendChild(ptag);
        };
    }

    function send() {
        var message = document.getElementById('send_str').value;
        var send_str = {
            from_user: document.getElementById('nick').value,
            // to_user:document.getElementById('to_user').value,
            to_user: 'all',   // 群聊
            message: message
        };
        var json_str = JSON.stringify(send_str);
        ws.send(json_str);
    }

    function sin_send() {
        var message = document.getElementById('send_str').value;
        var send_str = {
            from_user: document.getElementById('nick').value,
            to_user:document.getElementById('to_user').value,

            message: message
        };
        var json_str = JSON.stringify(send_str);
        ws.send(json_str);
    }

    // js代码是异步代码;
</script>
</html>

 

posted @ 2019-03-30 14:07  追风zz  阅读(169)  评论(0编辑  收藏  举报