我有一个网页应该使用Tornado WebSocket从Python服务器更新其内容。
我的问题
Tornado Server回复
304
并打印(例如:' Hello')当且仅当请求来自直接访问时(我的意思是发送请求)手动,在网页之外:192.168.8.103:8888
)当我尝试从网页打开WebSocket时,Torando Server会回复
200
并且无法打印消息(例如:' Hello')作为附加图像。
龙卷风脚本(服务器):
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)
}
我已经搜索了三天没有结果的解决方案:( ...我很感激任何帮助,非常感谢大家