Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/449.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么服务器每1秒而不是每100ms更新一次客户端-完整的源代码可用_Javascript_Python_Websocket_Twisted - Fatal编程技术网

Javascript 为什么服务器每1秒而不是每100ms更新一次客户端-完整的源代码可用

Javascript 为什么服务器每1秒而不是每100ms更新一次客户端-完整的源代码可用,javascript,python,websocket,twisted,Javascript,Python,Websocket,Twisted,我的服务器设置为每100ms勾选并更新所有客户端-请参阅self.TICKS\u PER\u SECOND=10,1000/10=100ms 然而,html中的“时钟”仅每1秒更新一次。为什么? 如果我一直点击提交按钮,时钟就会更新得更快。为什么? app.py import logging import sys from datetime import datetime import time current_milli_time = lambda: int(round(time.time()

我的服务器设置为每100ms勾选并更新所有客户端-请参阅
self.TICKS\u PER\u SECOND=10
,1000/10=100ms

然而,html中的“时钟”仅每1秒更新一次。为什么?

如果我一直点击提交按钮,时钟就会更新得更快。为什么?

app.py

import logging
import sys
from datetime import datetime
import time
current_milli_time = lambda: int(round(time.time() * 1000))

import json
import threading

from twisted.web.static import File
from twisted.python import log
from twisted.web.server import Site
from twisted.web.resource import Resource

from twisted.internet import pollreactor
pollreactor.install()

from twisted.internet import reactor

from autobahn.twisted.websocket import WebSocketServerFactory, \
    WebSocketServerProtocol

from autobahn.twisted.resource import WebSocketResource


class AppGameServerProtocol(WebSocketServerProtocol):

    def onOpen(self):
        """
        """
        self.factory.register(self)
        self.factory.onConnected(self)

    def onConnect(self, request):
        print("Client connecting: {}".format(request.peer))

    def connectionLost(self, reason):
        self.factory.unregister(self)

    def onMessage(self, payload, isBinary):
        self.factory.communicate(self, payload, isBinary)


class AppGameFactory(WebSocketServerFactory):

    def __init__(self, *args, **kwargs):
        super(AppGameFactory, self).__init__(*args, **kwargs)
        self.clients = {}

    def register(self, client):
        self.clients[client.peer] = {"object": client, "partner": None}

    def unregister(self, client):
        self.clients.pop(client.peer)


    def onConnected(self,client):
        client.sendMessage(json.dumps({"type": "connect"}))

    def communicate(self, client, payload, isBinary):
        print "msg received", payload

    def sendMessageAll(self, message):
        for i in self.clients:
            c = self.clients[i]
            c["object"].sendMessage(message)

class SummingThread(threading.Thread):
    def __init__(self, fac):
        super(SummingThread, self).__init__()
        self.fac = fac

        self.TICKS_PER_SECOND = 10
        self.SKIP_TICKS = 1000 / self.TICKS_PER_SECOND
        self.MAX_FRAMESKIP = 5
        self.loops = 0
        self.next_game_tick = current_milli_time()

    def run(self):
        while True:
            self.loops = 0
            while current_milli_time() > self.next_game_tick and self.loops < self.MAX_FRAMESKIP:

                self.fac.sendMessageAll("clock: " + datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])
                self.next_game_tick += self.SKIP_TICKS
                self.loops += 1



if __name__ == "__main__":
    log.startLogging(sys.stdout)

    factory = AppGameFactory(u"ws://127.0.0.1:8080")
    factory.protocol = AppGameServerProtocol
    resource = WebSocketResource(factory)

    root = Resource()
    root.putChild('', File('index.html'))

    root.putChild(u"ws", resource)

    thread1 = SummingThread(factory)
    thread1.start()

    try:
        site = Site(root)
        reactor.listenTCP(8080, site)
        reactor.run()
    except Exception as e:
        logging.exception("message")
导入日志
导入系统
从日期时间导入日期时间
导入时间
当前时间=lambda:int(四舍五入(time.time()*1000))
导入json
导入线程
从twisted.web.static导入文件
从twisted.python导入日志
从twisted.web.server导入站点
从twisted.web.resource导入资源
从twisted.internet导入
pollreactor.install()
从twisted.internet导入
从autobahn.twisted.websocket导入WebSocketServerFactory\
WebSocketServerProtocol
从autobahn.twisted.resource导入WebSocketResource
类AppGameServerProtocol(WebSocketServerProtocol):
def onOpen(自我):
"""
"""
self.factory.register(self)
self.factory.onConnected(self)
def onConnect(自我、请求):
打印(“客户端连接:{}”。格式(request.peer))
def connectionLost(自身、原因):
self.factory.unregister(self)
def onMessage(self、payload、isBinary):
self.factory.communication(self、有效负载、isBinary)
类AppGameFactory(WebSocketServerFactory):
定义初始化(self,*args,**kwargs):
super(AppGameFactory,self)。\uuuuuuuuuuuuuuuuuuuu初始(*args,**kwargs)
self.clients={}
def寄存器(自身、客户端):
self.clients[client.peer]={“object”:client,“partner”:None}
def注销(自我、客户端):
self.clients.pop(client.peer)
def未连接(自身、客户端):
client.sendMessage(json.dumps({“type”:“connect”}))
def通信(自身、客户端、有效负载、isBinary):
打印“收到消息”,有效载荷
def sendMessageAll(自我,消息):
对于self.clients中的i:
c=自我客户机[i]
c[“对象”].sendMessage(消息)
类SummingThread(threading.Thread):
定义初始(自我,fac):
super(SummingThread,self)。\uuu init\uuu()
self.fac=fac
self.TICKS\u/s=10
self.SKIP_TICKS=每秒1000个/self.TICKS_
self.MAX_FRAMESKIP=5
self.loops=0
self.next\u game\u tick=当前\u milli\u时间()
def运行(自):
尽管如此:
self.loops=0
当前\u milli\u time()>self.next\u游戏\u勾选和self.loops
index.html

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
        window.addEventListener("load", function() {

            var msgReceived = 0

            // create websocket instance
            var mySocket = new WebSocket("ws://localhost:8080/ws");

            // add event listener reacting when message is received
            mySocket.onmessage = function (event) {
                var output = document.getElementById("output");
                // put text into our output div
                msgReceived++;
                output.textContent = event.data + " msgReceived: " + msgReceived;
                //console.log(event.data);
            };

            var form = document.getElementsByClassName("foo");
            var input = document.getElementById("input");

            form[0].addEventListener("submit", function (e) {
                // on forms submission send input to our server
                input_text = input.value;
                mySocket.send(input_text);
                e.preventDefault()
            })
        });

    </script>
<style>
    /* just some super ugly css to make things bit more readable*/
    div {
        margin: 2em;
    }
    form {
        margin: 2em;
    }
</style>
</head>
<body>
    <form class="foo">
        <input id="input"></input>
        <input type="submit"></input>
    </form>
    <div id="output"></div>
</body>
</html>

addEventListener(“加载”,函数(){
var msgReceived=0
//创建websocket实例
var mySocket=newwebsocket(“ws://localhost:8080/ws”);
//添加接收到消息时作出反应的事件侦听器
mySocket.onmessage=函数(事件){
var output=document.getElementById(“输出”);
//将文本放入我们的输出div
msgReceived++;
output.textContent=event.data+“msgReceived:”+msgReceived;
//console.log(事件数据);
};
var form=document.getElementsByClassName(“foo”);
var输入=document.getElementById(“输入”);
表格[0]。addEventListener(“提交”,函数(e){
//提交表单时,将输入发送到我们的服务器
input_text=input.value;
发送(输入文本);
e、 预防默认值()
})
});
/*只是一些超级丑陋的css,让东西更可读*/
div{
边缘:2米;
}
形式{
边缘:2米;
}

您正在从多个线程调用Twisted API。这是不允许的。您只能从反应器线程调用Twisted API——除了几个特定的线程安全API。主要是
reactor.callFromThread
,它调度函数在reactor线程中运行

考虑将
SummingThread
替换为基于
twisted.internet.task.LoopingCall
的构造

例如:

from twisted.internet.task import LoopingCall

def game_tick(factory, skip_count):
    now = datetime.utcnow()
    factory.sendMessageAll(
        "clock: " + now.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
    )


factory = # ...
task = LoopingCall.withCount(partial(game_tick, factory))
task.start(0.1)
# ...
reactor.run()
game_tick
每秒将调用十次(或者,如果由于负载过高或其他问题而调用频率较低,
skip_count
将设置为大于一,以指示错过了多少次tick)