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>indextitle>
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的时候

     WebSocket群聊与单聊_第1张图片

 

  WebSocket群聊与单聊_第2张图片

  try之后  

  WebSocket群聊与单聊_第3张图片

二 . 单聊

  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/')
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>Titletitle>
head>
<body>

<p>发送者<input type="text" id="username">
    <button onclick="open_chat()">开始聊天button>  
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>

  展示结果:

  WebSocket群聊与单聊_第4张图片         WebSocket群聊与单聊_第5张图片

 

转载于:https://www.cnblogs.com/attila/p/10713901.html

你可能感兴趣的:(网络,json,python)