WebSocket群聊与单聊

一 . WebSocket实现群聊

  py文件代码

# py文件
from flask import Flask, render_template, request
from geventwebsocket.handler import WebSocketHandler
from geventwebsocket.websocket import WebSocket
from geventwebsocket.exceptions import WebSocketError
from gevent.pywsgi import WSGIServer  

app = Flask(__name__)

user_socket_list = []

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

@app.route('/my/ws')
def my_ws():
    # 当前端声明WebSocket的时候才有wsgi.websocket
    user_socket = request.environ.get('wsgi.websocket')  # type:WebSocket   # 为了让下面user_socket点的时候有提示
    user_socket_list.append(user_socket)
    print(len(user_socket_list), user_socket_list)

    while 1:
        try:   # 下面用图解释为什么要try
            msg = user_socket.receive()  # 阻塞等待发送信息
        except WebSocketError:
            user_socket_list.remove(user_socket)
            return 'GoodBye'
        for user in user_socket_list:
            if user == user_socket:
                continue
            try:
                user.send(msg)
            except:
                continue

if __name__ == '__main__':
    # 用下面这种方法启动是为了识别并支持websocket
    http_server = WSGIServer(('0.0.0.0', 9527), app, handler_class=WebSocketHandler)
    http_server.serve_forever()

  html代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>
<p><input type="text" id="message">
    <button onclick="send_message()">发送</button>
</p>
<div id="chat_list">

</div>
</body>
<script type="application/javascript">
    var ws = new WebSocket('ws://127.0.0.1:9527/my/ws');
    ws.onmessage = function (MessageEvent) {   //当接收到消息的时候执行MessageEvent函数
        var p = document.createElement('p');   // 创建一个p标签
        p.innerText = MessageEvent.data;    // 给p标签里面添加数据
        document.getElementById('chat_list').appendChild(p);  // 把p标签添加到div标签里面
    };

    function send_message() {
        var message = document.getElementById('message').value;
        ws.send(message)
    }
</script>
</html>

  不try的时候

     

 

  

  try之后  

  

二 . 单聊

  py文件

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

app = Flask(__name__)
user_socket_dict = {}

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

@app.route('/my/ws/<username>')
def my_ws(username):
    user_socket = request.environ.get('wsgi.websocket')  # type:WebSocket
    user_socket_dict[username] = user_socket
    print(len(user_socket_dict), user_socket_dict)
    while 1:
        try:
            msg = user_socket.receive()  # 阻塞等待消息
            # print(msg, type(msg))
            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)
        except WebSocketError:
            user_socket_dict.pop(username)
            return 'GoodBye'

if __name__ == '__main__':
    http_server = WSGIServer(('0.0.0.0', 9527), app, handler_class=WebSocketHandler)
    http_server.serve_forever()

  html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<p>发送者<input type="text" id="username">
    <button onclick="open_chat()">开始聊天</button>  <!--onclick就是点击执行里面函数-->
</p>
<p>接受者 <input type="text" id="to_user"></p>
<p>
    消息 <input type="text" id="message">
    <button onclick="SendMessage()">发送</button>      
</p>
<div id="chat_list">

</div>
</body>
<script type="application/javascript">
    var ws = null;   //声明一个全局变量
    function open_chat() {
        var username = document.getElementById('username').value;
        ws = new WebSocket('ws://127.0.0.1:9527/my/ws/' + username);
        ws.onopen = function () {   // onopen函数就是当你连接开始时执行
            alert('欢迎' + username + '来到午夜激情聊天室!')
        };
        ws.onmessage = function (MessageEvent) {
            var chat = JSON.parse(MessageEvent.data);
            var p = document.createElement('p');
            p.style.cssText = 'width:270px;text-align: left';
            p.innerText = chat.from_user + '->' + chat.message;
            document.getElementById('chat_list').appendChild(p);
        };
        ws.onclose = function () {  // onclose函数就是如果断开连接了执行函数
            // 断开连接
            console.log('已经断开连接');
        };
    }

    function SendMessage() {
        var message = document.getElementById('message').value;
        var from_user = document.getElementById('username').value;
        var to_user = document.getElementById('to_user').value;
        var send_str = {
            from_user: from_user,
            to_user: to_user,
            message: message
        };
        ws.send(JSON.stringify(send_str));
        var p = document.createElement('p');
        p.style.cssText = 'width:270px;text-align:right';
        p.innerText = send_str.message + '<-大帅比';
        document.getElementById('chat_list').appendChild(p);
    }
</script>
</html>

  展示结果:

           

 

posted @ 2019-04-15 22:45  一个很善良的抱爱  阅读(427)  评论(0编辑  收藏  举报