嘿,我是新来的蟒蛇,这里是在龙卷风WebSocket的服务器代码如何发送服务器信息给特定的客户端在龙卷风的WebSocket
import tornado.ioloop
import tornado.web
import tornado.websocket
import tornado.template
class MainHandler(tornado.web.RequestHandler):
def get(self):
loader = tornado.template.Loader(".")
self.write(loader.load("index.html").generate())
class WSHandler(tornado.websocket.WebSocketHandler):
def open(self):
print 'connection opened...'
self.write_message("The server says: 'Hello'. Connection was accepted.")
def on_message(self, message):
self.write_message("The server says: " + message + " back at you")
print 'received:', message
def on_close(self):
print 'connection closed...'
application = tornado.web.Application([
(r'/ws', WSHandler),
(r'/', MainHandler),
(r"/(.*)", tornado.web.StaticFileHandler, {"path": "./resources"}),
])
if __name__ == "__main__":
application.listen(9090)
tornado.ioloop.IOLoop.instance().start()
是否正常工作,并在服务器上收到我的消息(客户端的消息)但遗憾的是,它并没有向我发送其他客户信息。像我有这个网站
<!DOCTYPE html>
<html>
<head>
<title>WebSockets Client</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
</head>
<body>
Enter text to send to the websocket server:
<div id="send">
<input type="text" id="data" size="100"/><br>
<input type="button" id="sendtext" value="send text"/>
</div>
<div id="output"></div>
</body>
</html>
<script>
jQuery(function($){
if (!("WebSocket" in window)) {
alert("Your browser does not support web sockets");
}else{
setup();
}
function setup(){
// Note: You have to change the host var
// if your client runs on a different machine than the websocket server
var host = "ws://localhost:9090/ws";
var socket = new WebSocket(host);
console.log("socket status: " + socket.readyState);
var $txt = $("#data");
var $btnSend = $("#sendtext");
$txt.focus();
// event handlers for UI
$btnSend.on('click',function(){
var text = $txt.val();
if(text == ""){
return;
}
socket.send(text);
$txt.val("");
});
$txt.keypress(function(evt){
if(evt.which == 13){
$btnSend.click();
}
});
// event handlers for websocket
if(socket){
socket.onopen = function(){
//alert("connection opened....");
}
socket.onmessage = function(msg){
showServerResponse(msg.data);
}
socket.onclose = function(){
//alert("connection closed....");
showServerResponse("The connection has been closed.");
}
}else{
console.log("invalid socket");
}
function showServerResponse(txt){
var p = document.createElement('p');
p.innerHTML = txt;
document.getElementById('output').appendChild(p);
}
}
});
</script>
当我打从客户端发送按钮(使用上面的html)发给我的邮件服务器,但我想送我的信息给其他客户。如何将我的消息从服务器发送到其他客户端,如所需的客户端。 评论中给出的链接为我提供了一种方式(使全局列表变量,添加其中的每个客户端,然后在消息事件中循环并发送消息)将我的消息发送给所有客户端,但我也希望将消息发送给特定的客户端。
可能重复[Websockets with Tornado:从“外部”获取访问权限以将消息发送到客户端](https://stackoverflow.com/questions/23562465/websockets-with-tornado-get-access-from-the -outside-to-send-messages-to-clien) –
@BenDarnell你提供的链接,不包括如何发送消息到特定的客户端。 –
基本的解决方案是相同的 - 从'open'方法中保存对'self'的引用,然后稍后调用'write_message'。你如何识别客户是由你决定的。 –