无法从Web应用程序连接到Tornado Websocket:错误403

时间:2016-06-03 16:55:20

标签: websocket tornado

我有一个网页应该使用Tornado WebSocket从Python服务器更新其内容。

  1. 我使用PHP / MVC构建了网页
  2. 它与Local Apache完美配合(使用localhost访问页面)
  3. Tornado Server成功运行并处理所有收入请求
  4. 我在页面末尾添加了一个纯JavaScript来打开WebSocket
  5. 我的问题

      

    Tornado Server回复304并打印(例如:' Hello')当且仅当请求来自直接访问时(我的意思是发送请求)手动,在网页之外:192.168.8.103:8888

         

    当我尝试从网页打开WebSocket时,Torando Server会回复200并且无法打印消息(例如:' Hello')作为附加图像。

    Tornado error message (server-side)

    Web page error message

    龙卷风脚本(服务器):

    import tornado.httpserver
    import tornado.ioloop
    import tornado.options
    import tornado.web
    import tornado.websocket
    from tornado.options import define, options
    define("port", default=8888, help="run on the given port", type=int)
    class IndexHandler(tornado.web.RequestHandler):
        def get(self):
            self.write('Hello')
            #self.flush()
    class WebSocketHandler(tornado.websocket.WebSocketHandler):
        def open(self):
            print 'new connection'
            self.write_message("connected")
        def on_message(self, message):
            print 'message received %s' % message
            self.write_message('message received %s' % message)
        def on_close(self):
            print 'connection closed'
    if __name__ == "__main__":
        tornado.options.parse_command_line()
        app = tornado.web.Application(
            handlers=[
                (r"/", IndexHandler),
                (r"/ws", WebSocketHandler)
            ]
        )
        httpServer = tornado.httpserver.HTTPServer(app)
        httpServer.listen(options.port)
        print "Listening on port:", options.port
        tornado.ioloop.IOLoop.instance().start()
    

    WebSocket脚本(客户端):

    var socket = new WebSocket("ws://192.168.8.103:8888/ws");
      socket.onopen = function(){  
        console.log("connected"); 
      }; 
      socket.onmessage = function (message) {
        console.log("receiving: " + message.data);
      };
      socket.onclose = function(){
        console.log("disconnected"); 
      };
      sendMessage = function(message) {
        socket.send(message);
      };
      try{
          var value = 0;
          window.onload = function() {
          setInterval(function() {
            console.log('Sending Value: ' + value);
          sendMessage("{sensor: Ultra, value:" + value + "}");
          value += 10;
          },10000)
      };
      } catch(err)
        {
        alert("Error with creating the WebSocket"+err)
        }
    

    我已经搜索了三天没有结果的解决方案:( ...我很感激任何帮助,非常感谢大家

0 个答案:

没有答案