我正在使用 tornado websockets 来更新页面上的一些信息。如果用户更改屏幕上的某些内容,我希望将这些更改显示给所有其他具有活动连接的用户。我可以让 javascript 将消息发送到服务器,但我不知道如何将该消息发送回客户端。这是javascript和python
$(document).ready(function () {
var ws = new WebSocket("company website, I know this works");
ws.onopen = function () {
console.log("websocket engage");
};
ws.onmessage = $(".column li").on("mouseup", function (evt) {
pid = $(this).attr("id");
oldCid = $(this).parent().parent().attr("id");
newCid = $(this).parent().attr("id");
message = pid + " " + oldCid + " " + newCid;
ws.send(message);
});
ws.onclose = function (evt) {
console.log("connection closed");
};
ws.writemessage = function (evt) {
alert(evt.data);
};
});
这是python代码:
import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web
from tornado.options import define, options
define("port", default=8888, help="run on the given port", type=int)
change = "original"
listeners = []
class WSHandler(tornado.websocket.WebSocketHandler):
def open(self):
print "opened a new websocket"
listeners.append(self)
print listeners
def on_message(self, message):
#self.write_message(u"You Said: " + message)
print ("in on_message " + message)
change = message
#self.write_message(message)
def on_close(self):
print 'connection closed'
listeners.remove(self)
def write_message(self, message):
print ("in write message " + change)
self.write_message(change)
def main():
#tornado.options.parse_command_line()
application = tornado.web.Application([
(r'/ws', WSHandler),
])
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8888)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main()