嘿,我是新來的蟒蛇,這裏是在龍捲風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'。你如何識別客戶是由你決定的。 –