作为sockjs brukva使用异步服务器和客户端来识别和响应个人

时间:2012-11-21 22:21:53

标签: python websocket tornado sockjs

我正在构建一个实时Web应用程序。

我只想连接客户端,使用sockjs识别并向服务器发送不同的消息

我们到目前为止所做的是从浏览器连接并发送一条消息,我回答了同一台服务器。

当前代码

server.py

# -*- coding: utf-8 -*-
from sockjs.tornado import SockJSRouter, SockJSConnection
from tornado import web, ioloop

class ConnectionHandler(SockJSConnection):

    def on_open(self, info):
        print 'new connection'

    def on_message(self, msg):
        print str("server receives: %s" % msg)
        self.send(u"server responds: %s" % msg)

if __name__ == "__main__":
    onopen = SockJSRouter(ConnectionHandler, r"/websocket")

    application = web.Application(onopen.urls)

    application.listen(8686)
    ioloop.IOLoop.instance().start()

client.html

<!DOCTYPE html>
<html>
    <head>
        <title>SockJS</title>
    </head>
    <script src="http://cdn.sockjs.org/sockjs-0.3.min.js"></script>
    <script>
        con = new SockJS('http://localhost:8686/websocket');
        con.onmessage = function(evt){
            x = document.createElement("p");
            x.innerHTML = evt.data;
            document.getElementById("msgbox").appendChild(x);
        }
        function DispatchText(){
            var userInput = document.getElementById("message").value;
            document.getElementById("message").value = "";
            x = document.createElement("p");
            x.innerHTML = "message sent: " + userInput;
            document.getElementById("msgbox").appendChild(x);
            con.send(userInput);
        }
    </script>
    <body>
        <p style="width: 800px">Use form to communicate with the server.</p>
        <div id="msgbox" style="font-size: 14pt; height: 500px; width: 800px; overflow: scroll; border: 1px solid black"></div>
        <form id="communication" onsubmit="DispatchText()" action="javascript:void(0);">
            <input type="text" id="message" name="message" autocomplete="off" style="width:700px" />
            <input type="submit" id="sub" name="sub" value="send" style="width:90px" />
        </form>
    </body>
</html>

问题

如何识别每个客户?

将消息发送给所有连接的客户端?

1 个答案:

答案 0 :(得分:1)

您需要保留连接列表。现在,当收到消息时,它将被发送到所有连接的客户端:

class ConnectionHandler(SockJSConnection):
    connections = set()

    def on_open(self, info):
        print 'new connection'
        self.connections.add(self)

    def on_message(self, msg):
        print str("server receives: %s" % msg)

        for conn in self.connections:
            conn.send(u"server responds: %s" % msg)

        # Note you could also use self.broadcast(self.connections, msg)

    def on_close(self):
        self.connections.remove(self)