0

这是我正在使用的内容:

网络服务器.py:

import sys

from twisted.internet import reactor
from twisted.python import log

from autobahn.websocket import WebSocketServerFactory, \
                               WebSocketServerProtocol, \
                               listenWS


class EchoServerProtocol(WebSocketServerProtocol):

   def onMessage(self, msg, binary):
      print "sending echo:", msg
      self.sendMessage(msg, binary)


if __name__ == '__main__':

   log.startLogging(sys.stdout)

   factory = WebSocketServerFactory("ws://localhost:9000", debug = False)
   factory.protocol = EchoServerProtocol
   listenWS(factory)

   reactor.run()

背景.js:

function updateCookies(info) {
    send();
    console.log(info.cookie.domain);
}

function send() {
    msg = "TEST";
    sock.send(msg);
};

var sock = null;
sock = new WebSocket("ws://localhost:9000");
console.log("Websocket created...");

sock.onopen = function() {
    console.log("connected to server");
    sock.send("CONNECTED TO YOU");
}

sock.onclose = function(e) {
    console.log("connection closed (" + e.code + ")");
}

sock.onmessage = function(e) {
    console.log("message received: " + e.data);
}

chrome.cookies.onChanged.addListener(updateCookies);

现在,在运行 webserver.py 和运行 background.js 后,什么也没有发生。客户端看到没有回声,服务器没有报告任何连接或消息。但是,如果我重新加载 background.js,服务器会突然显示之前的“CONNECTED TO YOU”消息。再次重新加载会产生相同的效果,显示延迟的“CONNECTED TO YOU”消息。我在发送消息后尝试运行 sock.close() ,但这仍然没有产生任何结果。我真的很困惑是什么导致了这种随机延迟。让服务器运行 10 到 15 分钟也不会产生任何结果,我必须在看到任何消息之前手动刷新页面。知道可能是什么原因造成的吗?

4

0 回答 0