如何解决如何处理客户端与高速公路 websocket 的连接?
我正在开发一个程序,每当我在视频中检测到某个事件时,该程序就会通过 websocket(使用高速公路)将文本消息和图像发送到另一台计算机。问题是我只检测一次事件。我试图在停止程序或从客户端发送关闭握手之前暂停程序,但它没有改变任何东西。以下是客户端和服务器的部分代码。请注意,if 条件最初是在一个 while 循环中。如果有人有想法,我会欢迎。
客户:
import sys
from twisted.python import log
from twisted.internet import reactor
import time
from autobahn.twisted.websocket import WebSocketClientProtocol,\
WebSocketClientFactory
# import the base64 module
import base64
filename=""
class MyClientProtocol(WebSocketClientProtocol):
def onConnect(self,response):
print("Server connected: {0}".format(response.peer))
def onopen(self):
print("WebSocket connection open.")
def hello():
# opening the image file and encoding in base64
with open(filename,"rb") as image_file:
encoded_string = base64.b64encode(image_file.read())
# printing the size of the encoded image which is sent
print("Encoded size of the sent image: {0} bytes".format(len(encoded_string)))
# sending the encoded image
self.sendMessage(encoded_string)
self.sendClose()
hello()
def onMessage(self,payload,isBinary):
if isBinary:
print("Binary message received: {0} bytes".format(len(payload)))
else:
# printing the size of the encoded image which is received
print("Encoded size of the received image: {0} bytes".format(len(payload)))
def onClose(self,wasClean,code,reason):
print("WebSocket connection closed: {0}".format(reason))
if event:
cv2.imwrite(filename,frame)
log.startLogging(sys.stdout)
factory = WebSocketClientFactory("ws://localhost:9000")
factory.protocol = MyClientProtocol
reactor.connectTCP("192.168.0.37",9000,factory) #192.168.0.22
reactor.run()
time.sleep(5)
reactor.stop()
factory.stopFactory()
服务器:
from autobahn.twisted.websocket import WebSocketServerProtocol,\
WebSocketServerFactory
# import the base64 module
import base64
from datetime import datetime
class MyServerProtocol(WebSocketServerProtocol):
def onConnect(self,request):
print("Client connecting: {0}".format(request.peer))
def onopen(self):
print("WebSocket connection open.")
def onMessage(self,isBinary):
if isBinary:
print("Binary message received: {0} bytes".format(len(payload)))
else:
print("Text message received,saving to a file")
# decode the image and save locally
Now=datetime.Now()
name=Now.strftime("%d-%m-%Y %H:%M:%s")+".jpg"
with open(name,"wb") as image_file:
image_file.write(base64.b64decode(payload))
# echo back message verbatim
self.sendMessage(payload,isBinary)
def onClose(self,reason):
print("WebSocket connection closed: {0}".format(reason))
if __name__ == '__main__':
import sys
from twisted.python import log
from twisted.internet import reactor
log.startLogging(sys.stdout)
factory = WebSocketServerFactory("ws://localhost:9000",debug = False)
factory.protocol = MyServerProtocol
reactor.listenTCP(9000,factory)
reactor.run()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。