基于websocket的单聊.群聊

Posted 帅爆太阳的男人

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了基于websocket的单聊.群聊相关的知识,希望对你有一定的参考价值。

关于ai.baidu.com的 代码:

#########################################核心代码##############################################
from aip import AipNlp, AipSpeech
import os
from uuid import uuid4
import go_tuling

APP_ID = "15217709"
API_KEY = "eNiP5QUsgBh6QwpbNv8Qmsy3"
SECRET_RET = "gwhM3wDo0Kjjd1PDIxqqW4Bfex10Y4f3"

client = AipSpeech(APP_ID, API_KEY, SECRET_RET)
nlp_client = AipNlp(APP_ID, API_KEY, SECRET_RET)


# 读取文件
def get_file_content(filePath):
    # 格式转换将其他格式的文件转换成pcm文件
    os.system(f"ffmpeg -y -i {filePath} -acodec pcm_s16le -f s16le -ac 1 -ar 16000 {filePath}.pcm")
    with open(f"{filePath}.pcm", "rb")as fp:
        # 返回这个文件
        return fp.read()


# 音频变文本
def audio2text(filename):
    print("1", filename)
    # 是被本地文件
    res = client.asr(get_file_content(filename), "pcm", 16000, {
        "dev_pid": 1536,
    })
    print(res.get("result")[0])
    return res.get("result")[0]


# 文本变音频
def text2audio(A):
    result = client.synthesis(A, "zh", 1, {
        "per": 4,
        "pit": 8,
        "spd": 4,
        "vol": 5,
    })
    if not isinstance(result, dict):
        # 获取文件的文件名
        filename = f"{uuid4()}.mp3"
        # 文件的路径
        filepath = os.path.join("audios", filename)
        with open(filepath, "ab") as f:
            f.write(result)
        # 返回这个文件的名字
        return filename


# 获取到用户输入的响应文件
def my_nip(Q):
    # 判断用户输入的
    if nlp_client.simnet(Q, "你叫什么名字").get("score") >= 0.7:
        A = "我的名字叫雪人"
    else:
        # 获取图灵返回的文字
        A = go_tuling.tl(Q, "yuebanwan")

    # 返回这个图灵反应的文件
    return A

调用图灵的代码:

import requests
#########################################基本配置##########################
url = "http://openapi.tuling123.com/openapi/api/v2"

data_dict = {
    "reqType": 0,
    "perception": {
        "inputText": {
            "text": "北京"
        },
    },
    "userInfo": {
        "apiKey": "96dfe320eec549519c5168093f93b2dc",
        "userId": "yuebanwan"
    }
}


##################################执行函数#########################################
def tl(text, uid):
    # 给字典赋值text,这个text是传过来用户输入的内容
    data_dict["perception"]["inputText"]["text"] = text
    # 并给字典表名是哪个用户发来的请求
    data_dict["userInfo"]["userInfo"] = uid
    # 把消息数据返回给图灵,图灵并返回响应结果
    res = requests.post(url, json=data_dict)
    # 调用json方法把数据转成json格式的数据
    res_json = res.json()
    # 把图灵响应的数据
    return res_json.get("results")[0]["values"]["text"]

实例化AipNlp的代码:

from aip import AipNlp


APP_ID = "15217709"
API_KEY = "eNiP5QUsgBh6QwpbNv8Qmsy3"
SECRET_KEY = "gwhM3wDo0Kjjd1PDIxqqW4Bfex10Y4f3"

nlp_client = AipNlp(APP_ID, API_KEY, SECRET_KEY)

text1 = "你叫什么名字"

text2 = "您怎们称呼"

res = nlp_client.simnet(text1, text2)

# print(res.get("score"))

最终app的代码:

from flask import Flask,request, render_template, send_file, jsonify
from uuid import uuid4
from baidu_ai import audio2text
from baidu_ai import my_nip
from baidu_ai import text2audio
import os

# 实例化一个Flask的对象
app = Flask(__name__)

# 写一个路由
@app.route("/", methods=["GET", "POST"])
def index():
    if request.method == "GET":
        return render_template("web.html")


@app.route("/toy_uploader", methods=["GET", "POST"])
def toy_uploader():
    # 拼接路径
    file_path = os.path.join("audios", f"{uuid4()}.wav")
    #
    request.files["record"].save(file_path)
    # 将音频变成文本的函数,并的到音频的内容
    Q = audio2text(file_path)
    print(Q)
    # 调用aipNlp
    A = my_nip(Q)
    # 将图灵处理后的数据返回的文本
    filename = text2audio(A)
    print(filename)
    # 返回给前端json格式的数据
    return jsonify({"filename": filename, "A": A})


@app.route("/get_audio/<filename>", methods=["GET", "POST"])
def get_audio(filename):
    # 拼接新的路径
    new_file = os.path.join("audios", filename)
    print("2", new_file)
    # 返回给前端新的文件
    return send_file(new_file)


if __name__ == ‘__main__‘:
    app.run("192.168.12.49", 5000, debug=True)

前端代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<audio src="" controls autoplay id="player"></audio>
<p>
    <button onclick="start_reco()" style="background-color: red">录制消息</button>
</p>
<p>
    <button onclick="stop_reco()" style="background-color: green">发送消息</button>
</p>
</body>
<script type="text/javascript" src="/static/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="/static/Recorder.js"></script>
<script type="text/javascript">
    var serv = "http://192.168.12.49:5000";
    // var get_music = "http://192.168.1.102:9527/get_music/";
    // var get_chat = "http://192.168.1.102:9527/get_chat/";
    var reco = null;

    var audio_context = new AudioContext();
    navigator.getUserMedia = (navigator.getUserMedia ||
        navigator.webkitGetUserMedia ||
        navigator.mozGetUserMedia ||
        navigator.msGetUserMedia);

    navigator.getUserMedia({audio: true}, create_stream, function (err) {
        console.log(err)
    });

    function create_stream(user_media) {
        var stream_input = audio_context.createMediaStreamSource(user_media);
        reco = new Recorder(stream_input);
    }

    function start_reco() {
        reco.record();
    }

    function stop_reco() {
        reco.stop();
        get_audio();
        reco.clear();
    }

    function get_audio() {
        reco.exportWAV(function (wav_file) {
            // wav_file = Blob对象 file对象
            // ws.send(wav_file);
            var formdata = new FormData();
            formdata.append("record", wav_file);
            // formdata.append("sender", toy_id);
            // formdata.append("to_user", document.getElementById("from_user").innerText);
            $.ajax({
                url: serv + "/toy_uploader",
                type: ‘post‘,
                processData: false,
                contentType: false,
                data: formdata,
                dataType: ‘json‘,
                success: function (data) {
                    console.log(data.A);
                    // console.log(data);

                    document.getElementById("player").src =
                        "http://192.168.12.49:5000/get_audio/" + data.filename;


                }
            });

        })
    }





</script>
</html>

群聊的代码:

from flask import Flask, request,render_template
from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer

from geventwebsocket.websocket import WebSocket

# 实例化一个app对象
app = Flask(__name__)  # type: Flask
# 准备一个存放连接用户的容器
user_socket_list = []

@app.route("/ws")
def ws():
    user_socket = request.environ.get("wsgi.websocket")  # type: WebSocket
    if user_socket:
        # 把已经连接的用户添加到用户的连接列表中
        user_socket_list.append(user_socket)
    # print(len(user_socket_list), user_socket_list)
    while 1:
        # 获取到用户的数据
        msg = user_socket.receive()
        print(msg)
        for usocket in user_socket_list:
            if user_socket == usocket:
                continue
            try:
                usocket.send(msg)
            except:
                continue


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


if __name__ == ‘__main__‘:
    http_serv = WSGIServer(("192.168.12.49",5000), app, handler_class=WebSocketHandler)
    http_serv.serve_forever()

群聊的前端代码:

<!DOCTYPE html>
<html lang="zh-CN">
<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>
<p>发送内容:<input type="text" id="message"><button onclick="send_msg()">发送消息</button></p>
<div id="msg_list" style="width: 500px;">

</div>
</body>
<script type="application/javascript">
    var ws = new WebSocket("ws://192.168.12.49:5000/ws");
    // ws.onopen = function(){
    //   alert("欢迎来到S14群喷");
    // };
    ws.onmessage = function (ws_status) {
        console.log(ws_status.data);
        var ptag = document.createElement("p");
        ptag.innerText = ws_status.data;
        document.getElementById("msg_list").appendChild(ptag);
    };

    function send_msg() {
        var msg = document.getElementById("message").value;
        var ptag = document.createElement("p");
        ptag.style.cssText = "text-align: right;";
        ptag.innerText = msg;
        document.getElementById("msg_list").appendChild(ptag);
        ws.send(msg);
    }
</script>
</html>

单聊的代码:

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

# 实例化一个Flask对象
app = Flask(__name__)  # type:Flask

user_socket_dict = {

}

@app.route("/ws/<user>")
def ws(user):
    # 使用微博socket服务
    user_socket = request.environ.get("wsgi.websocket")  # type:WebSocket
    # 如果存在user_socket连接
    if user_socket:
        # 是该用户连接socket
        user_socket_dict[user] = user_socket
    print(len(user_socket_dict), user_socket_dict)

    while 1:
        # 接收到连接用户发过来的信息
        msg = user_socket.receive()
        print(msg)
        # 把收到的msg反序列化
        msg_dict = json.loads(msg)
        # 获取到反序列化的有效内容
        to_usocket = user_socket_dict.get(msg_dict.get("to_user"))
        # 发送给前端显示
        to_usocket.send(json.dumps({"from_user": user, "to_user": msg_dict.get("to_user"), "msg": msg_dict.get("msg")}))


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


if __name__ == ‘__main__‘:
    http_serv = WSGIServer(("192.168.12.49", 5000), app, handler_class=WebSocketHandler)
    http_serv.serve_forever()

单聊的前端代码:

<!DOCTYPE html>
<html lang="zh-CN">
<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>
<p>您的昵称:<input type="text" id="nick"><button onclick="openws()">进入聊天室</button></p>
<p>给<input type="text" id="to_user">发送:<input type="text" id="message"><button onclick="send_msg()">发送消息</button></p>
<div id="msg_list" style="width: 500px;">

</div>
</body>
<script type="application/javascript">
    var ws = null;
    // ws.onopen = function(){
    //   alert("欢迎来到S14群喷");
    // };

    function openws(){
        var nick = document.getElementById("nick").value;
        ws = new WebSocket("ws://192.168.12.49:5000/ws/"+nick);
        ws.onmessage = function (ws_status) {
            console.log(ws_status.data);
            var msg_obj = JSON.parse(ws_status.data);
            var ptag = document.createElement("p");
            ptag.innerText = msg_obj.from_user + " : " +msg_obj.msg;
            document.getElementById("msg_list").appendChild(ptag);
        };
    }

    function send_msg() {
        var msg = document.getElementById("message").value;
        var from_user = document.getElementById("nick").value;
        var to_user = document.getElementById("to_user").value;
        var ptag = document.createElement("p");
        ptag.style.cssText = "text-align: right;";
        ptag.innerText = msg + " : "+ from_user;
        document.getElementById("msg_list").appendChild(ptag);
        var msg_obj = {
            msg:msg,
            from_user:from_user,
            to_user:to_user
        };
        ws.send(JSON.stringify(msg_obj));
    };

</script>
</html>

Websocket代码:

解密代码:

 1 # b‘x81x83xceHxb6x85xffzx85‘
 2 
 3 hashstr = b‘x81x83xceHxb6x85xffzx85‘
 4 # b‘x81    x83    xceHxb6x85xffzx85‘
 5 
 6 # 将第二个字节也就是 x83 第9-16位 进行与127进行位运算
 7 payload = hashstr[1] & 127
 8 print(payload)
 9 if payload == 127:
10     extend_payload_len = hashstr[2:10]
11     mask = hashstr[10:14]
12     decoded = hashstr[14:]
13 # 当位运算结果等于127时,则第3-10个字节为数据长度
14 # 第11-14字节为mask 解密所需字符串
15 # 则数据为第15字节至结尾
16 
17 if payload == 126:
18     extend_payload_len = hashstr[2:4]
19     mask = hashstr[4:8]
20     decoded = hashstr[8:]
21 # 当位运算结果等于126时,则第3-4个字节为数据长度
22 # 第5-8字节为mask 解密所需字符串
23 # 则数据为第9字节至结尾
24 
25 
26 if payload <= 125:
27     extend_payload_len = None
28     mask = hashstr[2:6]
29     decoded = hashstr[6:]
30 
31 # 当位运算结果小于等于125时,则这个数字就是数据的长度
32 # 第3-6字节为mask 解密所需字符串
33 # 则数据为第7字节至结尾
34 
35 str_byte = bytearray()
36 
37 for i in range(len(decoded)):
38     byte = decoded[i] ^ mask[i % 4]
39     str_byte.append(byte)
40 
41 print(str_byte.decode("utf8"))

加密:

 1 import struct
 2 msg_bytes = "hello".encode("utf8")
 3 token = b"x81"
 4 length = len(msg_bytes)
 5 
 6 if length < 126:
 7     token += struct.pack("B", length)
 8 elif length == 126:
 9     token += struct.pack("!BH", 126, length)
10 else:
11     token += struct.pack("!BQ", 127, length)
12 
13 msg = token + msg_bytes
14 
15 print(msg)

 

以上是关于基于websocket的单聊.群聊的主要内容,如果未能解决你的问题,请参考以下文章

python-flask复习——- flask请求上下文源码解读http聊天室单聊/群聊(基于gevent-websocket)

websocket实现群聊和单聊(转)

spring websocket 和socketjs实现单聊群聊,广播的消息推送详解

javascript基于websocketnodejsuniapp的聊天室

javascript基于websocketnodejsuniapp的聊天室

好大一波,波波都大#spring boot websocket单聊+群聊#