2017-10-19 92 views
0

嘿,我是新來的蟒蛇,這裏是在龍捲風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)發給我的郵件服務器,但我想送我的信息給其他客戶。如何將我的消息從服務器發送到其他客戶端,如所需的客戶端。 評論中給出的鏈接爲我提供了一種方式(使全局列表變量,添加其中的每個客戶端,然後在消息事件中循環併發送消息)將我的消息發送給所有客戶端,但我也希望將消息發送給特定的客戶端。

+0

可能重複[Websockets with Tornado:從「外部」獲取訪問權限以將消息發送到客戶端](https://stackoverflow.com/questions/23562465/websockets-with-tornado-get-access-from-the -outside-to-send-messages-to-clien) –

+0

@BenDarnell你提供的鏈接,不包括如何發送消息到特定的客戶端。 –

+0

基本的解決方案是相同的 - 從'open'方法中保存對'self'的引用,然後稍後調用'write_message'。你如何識別客戶是由你決定的。 –

回答

0

你需要一些外部系統來做到這一點。就像本·達內爾說的那樣,其他問題解釋了一些原始的方式來聚集顧客。

您需要的是在初始化時收集每個客戶端的某種ID。這可能是從您的系統中的帳戶,或者您也可以生成爲每個新連接新:

import uuid 

clients = {} 

class WSHandler(tornado.websocket.WebSocketHandler): 
    def __init__(self, application, request, **kwargs): 
     super(WSHandler, self).__init__(application, request, **kwargs) 
     self.client_id = str(uuid.uuid4()) 

    def open(self): 
     print 'connection for client {0} opened...'.format(self.client_id) 
     clients[self.client_id] = self 
     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): 
     clients.pop(self.client_id, None) 
     print 'connection closed...' 

以後,你可以用這個完全由client_id告訴其他客戶端與該ID的客戶端存在。稍後,您可以通過發送消息給他

clients[<id>].write_message("Hello!") 

作爲一個附註,雖然這種方法不能很好地擴展。事實上,您只能解決僅連接到當前龍捲風實例的客戶端。如果您需要多個實例以及聯繫任何客戶端的方法,請參閱消息代理,如rabbitmq

相關問題