我试图通过websockets创建一个客户端来编写一些测试用例来评估服务器的响应。我用高速公路建立联系。但是,由于我当前无法发送消息,因此我无法在该类中发送消息。代码如下:
class SlowSquareClientProtocol(WebSocketClientProtocol):
def onOpen(self):
print "Connection established"
def onMessage(self, payload, isBinary):
if not isBinary:
res = json.loads(payload.decode('utf8'))
print("Result received: {}".format(res))
self.sendClose()
def onClose(self, wasClean, code, reason):
if reason:
print(reason)
reactor.stop()
class NLVRTR(TestFixture,SlowSquareClientProtocol):
@classmethod
def setUpClass(self):
log.startLogging(sys.stdout)
factory = WebSocketClientFactory(u"ws://someURL:8078")
factory.protocol = SlowSquareClientProtocol
reactor.connectTCP("someURL", 8078, factory)
wsThread = threading.Thread(target = reactor.run,
kwargs={'installSignalHandlers':0})
wsThread.start()
def test_00_simple(self):
WSJsonFormatter = WSformat()
x = WSJsonFormatter.formatGetInfo(2)
self.sendMessage(json.dumps(x).encode('utf8'))
print("Request to square {} sent.".format(x))
因此,为了详细说明,我在setUpClass方法中启动了客户机,并尝试在test_00_simple中发送一些消息。然而,我似乎遇到了这样的错误
^{pr2}$状态应该是在WebSocketClientProtoco中定义的属性。如果我将sendmessage放在onOpen方法中,一切都会正常工作,但是除了SlowSquareClientProtocol类之外,我不能从其他任何地方调用它。在高速公路的文件中提到
Whenever a new client connects to the server, a new protocol instance will be created
我认为这就是问题所在,它会创建一个新的协议实例,sendmages方法正在使用该实例。既然我不是在慢车里叫它。。。类时,sendmessage在客户端连接时从未捕捉到此新创建的协议,因此出现错误。我的问题是,有没有什么方法可以在客户端连接后通过代码获取新创建的实例?在
我发现了一个愚蠢的方法来解决这个问题,使用垃圾收集器来检索实例,如下所示
因此,我搜索了所有具有我要查找的类名称的实例,然后在sendmessage方法中传递它。我仍然愿意接受其他更简单的建议:)
相关问题 更多 >
编程相关推荐