我已经启动了一个项目,该项目需要并使用websocket来按预期将信息从服务器X发送到客户端Y。
但是,我一直遇到一个问题,即每20秒钟左右会断开一次连接,因为这就是TCP / IP的本意,所以我需要自己发送 heartbeats 。< / p>
在继续之前,如果还有其他方法(除了发送心跳信号),请告诉我。
因此,在发送心跳之前,我要制作网络套接字的方法是这样的:
from tkinter import *
class frame(Frame):
def __init__(self,display):
Frame.__init__(self,display)
l = Label(self,text="frame1")
l.pack()
class frame2(Frame):
def __init__(self,display):
Frame.__init__(self,display)
l = Label(self,text="frame2")
l.pack()
class test(Tk):
def __init__(self):
Tk.__init__(self)
f2 = frame2(self)
f2.grid(row=0)
#To raise the first frame, I used the following
frame2.grid_remove()
f = frame(self)
f.grid(row=0)
t = test()
t.mainloop()
async def listener(websocket, path, service):
command = service['log_command']
p = subprocess.Popen(command, stdout=subprocess.PIPE, bufsize=1, shell=True)
prev_sd = "-1"
await heartbeat_manager(websocket)
asyncio.sleep(5)
while True:
await websocket.send(p.stdout.readline())
之后就是我们所关心的一切,我的意图是让Websocket每5秒发送一次心跳某些文本,但根本不知道从哪里开始。
旁注:我调用的另一个函数实际上运行此websocket,但它与问题无关,因此我没有包括它,但请放心;它确实存在(并且所有这些代码都具有功能,但在死亡之前仅持续20秒钟)。
答案 0 :(得分:0)
Since you're using Python's async/await mechanism, perhaps you could try using asyncio subprocesses to let you await a subprocess's output streams. The following example code spawns the subprocess and checks for new lines available on standard output with a 5 second timeout, using asyncio.wait_for()
; if no data is available to send, we deliver a heartbeat instead.
import asyncio
async def listener(websocket, path, service):
command = service['log_command']
p = await asyncio.create_subprocess_shell(command, stdout=asyncio.subprocess.PIPE)
...
while True:
try:
data = await asyncio.wait_for(p.stdout.readline(), timeout=5)
websocket.send(data)
except asyncio.TimeOutError:
await websocket.send("heartbeat")