0

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

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

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

当前代码

服务器.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()

客户端.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>

问题

如何识别每个客户?

作为向单个客户端发送消息,所有连接的人?

4

1 回答 1

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)
于 2012-11-21T23:30:05.483 回答