我无法弄清楚为什么socket在Windows平台上关闭。
以下简单的服务器可以在我的linux机箱(chrome和firefox)上运行,但不能在我的Windows机箱或Android手机上,我只看到消息“socket closed”。这个chat demo可以在我尝试的所有平台上找到。谢谢你的任何建议。
贾斯汀
----服务器代码:------
import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web
import time
class WSHandler(tornado.websocket.WebSocketHandler):
def open(self):
print 'new connection'
self.write_message("Hello World")
for i in range(3):
self.write_message('Testing %d' % i)
i += 1
time.sleep(1)
self.close()
def on_message(self, message):
print 'message received %s' % message
def on_close(self):
print 'connection closed'
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.render("logdemo.html")
application = tornado.web.Application([
(r'/', MainHandler),
(r'/ws', WSHandler),
])
if __name__ == "__main__":
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8888)
print 'serving on port 8888'
tornado.ioloop.IOLoop.instance().start()
---- logdemo.html ----
<!doctype html>
<html>
<head>
<script src="http://code.jquery.com/jquery.min.js"></script>
<script>
function log(m) {
d = document.getElementById("log");
d.innerHTML = m + "<br/>" + d.innerHTML;
}
$(document).ready(function () {
var ws = new WebSocket("ws://raspberrypi.local:8888/ws");
ws.onopen = function(evt) { log("socket opened"); };
ws.onmessage = function(evt) { log("message: " + evt.data); ws.send("GOTIT");};
ws.onclose = function(evt) { log("socket closed"); };
});
</script>
</head>
<body>
<h1>Websockets Streaming</h1>
<div id="log"></div>
</body>
</html>
答案 0 :(得分:1)
您正在WSHandler的open方法中调用self.close()。 我相信这就是原因,不是吗?