Tornadao—WebSocket(聊天机器人)

目录

  1. 逻辑
  2. 配置
  3. 页面

  • 逻辑


    import json
    
    import requests   # 第三方库,负责发起请求,需要安装: pip install requests
    import tornado.web
    import tornado.ioloop
    import tornado.options
    import tornado.websocket
    from settings import config
    
    
    tornado.options.define('port',default=9000,type=int)
    
    class ClientHandler(tornado.web.RequestHandler):
        def get(self):
            self.render("chat.html")
    
    ws_client = set()
    
    class ServerHandler(tornado.websocket.WebSocketHandler):
        def open(self,*args):
            ws_client.add(self)
    
        # 接收客户端发过来的消息
        def on_message(self, message):
            print(message)
            dict1 = {
                "reqType":0,
                "perception": {
                    "inputText": {
                        "text": message
                    },
                },
                "userInfo": {
                    "apiKey": "自己的apikey",
                    "userId": "自己的"
                }
            }
            # 把来自客户端的信息发送给图灵机器人
            res = requests.post(url="http://openapi.tuling123.com/openapi/api/v2",
                                json=dict1)
            # 获取返回的消息
            # print(res.text)
            res = json.loads(res.text)  # 转换为字典
            print(res)
            res = res["results"][0]["values"]["text"]
            print(res)
            # 回复客户端
            self.write_message(res)
    
    
        def on_close(self):
            ws_client.remove(self)
    
    
    
    
    def main():
        app = tornado.web.Application(
            [(r'/',ClientHandler),
             (r'/ws',ServerHandler),
             ],
            **config
        )
        server = tornado.web.HTTPServer(app)
        server.listen(tornado.options.options.port)
        tornado.ioloop.IOLoop.current().start()
    
    if __name__ == '__main__':
        main()
  • 配置


    # settings.py
    
    config = {
        'debug':True,
        'static_path':"static",
        'template_path':'templates',
    }
    
  • 页面


    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>聊天</title>
    </head>
    <body>
    <input type="text" name="msg" id="msg"> <input type="button" value="说" id="speak">
    <div id="content">
    
    </div>
    </body>
    </html>
    <script src="https://cdn.bootcss.com/jquery/1.12.3/jquery.slim.min.js"></script>
    <script>
        var ws = new WebSocket('ws://127.0.0.1:9000/ws');
        $("#speak").click(function(){
            // 获取信息
            msg = $("#msg").val();
            // 发行信息给服务器
            ws.send(msg)
        })
        // 接收服务器端发过来的信息
        ws.onmessage = function(evt){
            $("#content").append("<p>"+evt.data+"</p>")
        }
    </script>
发布了257 篇原创文章 · 获赞 6 · 访问量 3522

猜你喜欢

转载自blog.csdn.net/piduocheng0577/article/details/105069513