web_socket

web_socket+Flask实现网页版聊天

服务器端:

import json

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__)

user_socket_dict = {}
# user_socket_dict = []

@app.route('/conn_ws/<user>')
def ws_app(user):
    # print(request.environ) 
  ''' ws:// {'GATEWAY_INTERFACE': 'CGI/1.1', 'SERVER_SOFTWARE': 'gevent/1.4 Python/3.7', 'SCRIPT_NAME': '', 'wsgi.version': (1, 0), 'wsgi.multithread': False, 'wsgi.multiprocess': False, 'wsgi.run_once': False, 'wsgi.url_scheme': 'http', 'wsgi.errors': <_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'>, 'SERVER_NAME': 'changtao', 'SERVER_PORT': '9527', 'REQUEST_METHOD': 'GET', 'PATH_INFO': '/conn_ws', 'QUERY_STRING': '', 'SERVER_PROTOCOL': 'HTTP/1.1', 'REMOTE_ADDR': '192.168.11.181', 'REMOTE_PORT': '58068', 'HTTP_HOST': '192.168.11.181:9527', 'HTTP_CONNECTION': 'Upgrade', 'HTTP_PRAGMA': 'no-cache', 'HTTP_CACHE_CONTROL': 'no-cache', 'HTTP_USER_AGENT': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36', 'HTTP_UPGRADE': 'websocket', 'HTTP_ORIGIN': 'http://localhost:63342', 'HTTP_SEC_WEBSOCKET_VERSION': '13', 'HTTP_ACCEPT_ENCODING': 'gzip, deflate', 'HTTP_ACCEPT_LANGUAGE': 'zh-CN,zh;q=0.9,en;q=0.8', 'HTTP_SEC_WEBSOCKET_KEY': 'p1otMQwA0qQcMd3FEJ5Kaw==', 'HTTP_SEC_WEBSOCKET_EXTENSIONS': 'permessage-deflate; client_max_window_bits', 'wsgi.input': <gevent.pywsgi.Input object at 0x0000023F6943A588>, 'wsgi.input_terminated': True, 'wsgi.websocket_version': '13', 'wsgi.websocket': <geventwebsocket.websocket.WebSocket object at 0x0000023F69377AD8>, 'werkzeug.request': <Request 'http://192.168.11.181:9527/conn_ws' [GET]>} ''' user_socket = request.environ.get("wsgi.websocket") # type:WebSocket # user_socket_dict.append(user_socket) user_socket_dict[user] = user_socket print(len(user_socket_dict), user_socket_dict) while True: msg = user_socket.receive() msg_dict = json.loads(msg) to_user = msg_dict.get("to_user") to_user_socket = user_socket_dict.get(to_user) to_user_socket.send(msg) # for i in user_socket_dict: # i.send(msg) @app.route("/") def index(): return render_template("my_ws.html") if __name__ == '__main__': http_serv = WSGIServer(("0.0.0.0", 9527), app, handler_class=WebSocketHandler) # 如果不是http请求,就交给WebSocketHandler http_serv.serve_forever()

  

前端:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p><input type="text" id="nick"><button onclick="login()">登陆聊天室</button></p>
<p>发送给谁:<input type="text" id="to_user"></p>
<p>
    消息:<input type="text" id="send_msg">
    <button id="send_btn" onclick="send()">发送消息</button>
</p>
<div id="show_msg">

</div>
</body>
<script type="text/javascript">
    var ws = null;
    {#var ws = new WebSocket("ws://192.168.11.181:9527/conn_ws");#}
    {#ws.onmessage=function (messageEvent) {#}
    {#    console.log(messageEvent.data);};#}
    {#var ws = new WebSocket("ws://192.168.11.181:9527/conn_ws");#}
    function login() {
        var nick = document.getElementById("nick").value;
        ws = new WebSocket("ws://192.168.11.181:9527/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 ;
            {#ptag.innerText =message.message;#}
            document.getElementById("show_msg").appendChild(ptag);
        };}
    function send() {
        var message = document.getElementById("send_msg").value;
        var send_str = {
            from_user:document.getElementById("nick").value,
            to_user:document.getElementById("to_user").value,
            message:message
        };
        var json_send_str = JSON.stringify(send_str);
        ws.send(json_send_str);
        var ptag = document.createElement("p");
        ptag.innerText =document.getElementById("nick").value + " : " + message;
        document.getElementById("show_msg").appendChild(ptag);
    }

</script>
</html>

  

 

posted @ 2019-05-09 20:32  Py浪涛  阅读(252)  评论(0编辑  收藏  举报
你想听歌吗o((;=゚ 3゚ =))o~♪