我不知道为什么套接字在 Windows 平台上关闭。
以下简单服务器适用于我的 linux 机器(chrome 和 firefox),但不适用于我的 windows 机器或 android 手机,我只看到“套接字关闭”消息。这个聊天演示可以在我尝试过的所有平台上找到。感谢您的任何建议。
贾斯汀
---- 服务器代码:-----
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>