python - 如何避免服务器(使用python websockets)挂断?
问题描述
我编写了一个使用 python 的 websockets 发送数据的服务器。该脚本在 Supervisord 上运行并且运行良好。突然之间,客户端无法从服务器获取任何东西。我停止了主管并尝试手动运行脚本,它工作得很好。我不确定我做错了什么。
服务器脚本:
from __future__ import print_function
#!/usr/bin/env python
import asyncio
import datetime
import random
import websockets
import ast
from collections import defaultdict
import csv
import datetime
from itertools import chain
import json
import os
import operator
import sys
import pymongo
from pymongo import MongoClient
try:
client = MongoClient('localhost', 27017)
db = client["Bubble"]
except Exception as e:
print(e)
start_match = datetime.datetime.strptime(
"2018-07-01 18:00:00", '%Y-%m-%d %H:%M:%S')
collection = "CRODEN_R16"
async def hello(websocket, path):
entity_name = await websocket.recv()
print(entity_name)
file = open("set_start_match.txt", "r")
for line in file:
start_today = datetime.datetime.strptime(
line.split('.')[0], '%Y-%m-%d %H:%M:%S')
print(start_today)
while True:
now = datetime.datetime.utcnow()
diff = now - start_today
request_match = start_match + diff
print(diff)
count = 0
for post in db[collection].find():
print(count)
if "emotion" not in post.keys():
print("Ignored")
continue
if post["timeStamp"] > request_match:
if post["entity_name"] == entity_name:
print("Satisfied")
currDict = {}
currDict["entity"] = post["entity_name"]
currDict["emotion"] = max(
post["emotion"].items(), key=operator.itemgetter(1))[0]
currDict["profile_image"] = post["userProfile"]
currDict["tweet"] = post["tweet"].encode('utf-8')
currDict_json = json.dumps(currDict, default=str)
print(currDict["tweet"])
await websocket.send(currDict_json)
del currDict
else:
print("Ignored")
await asyncio.sleep(1)
try:
start_server = websockets.serve(hello, '0.0.0.0', 8765)
print("Start entity server")
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
except Exception as e:
print(e)
客户代码:
#!/usr/bin/env python
# WS client example
import asyncio
import websockets
async def hello():
async with websockets.connect(
'ws://A.B.C.D:8765') as websocket:
name = input("What's your name? ")
await websocket.send(name)
while True:
greeting = await websocket.recv()
print(greeting)
asyncio.get_event_loop().run_until_complete(hello())
asyncio.get_event_loop().run_forever()
解决方案
推荐阅读
- c++ - Visual Studio 代码:C/C++:显示的头文件/包含文件的多个定义;怎么修?
- operating-system - 如何找出 I/O APIC 上的中断源?
- python - 使用 python 解析 JSON,来自 STDOUT 的多个条目
- mysql - 根据另一个表上的值过滤列
- flutter - 在颤动图中包装图例
- database - 使用 sqlloader 将特殊字符作为 �� 插入 Oracle 数据库
- javascript - 创建对象的生命周期
- c# - 我想从数据库中选择浮点值并在文本框(asp.net)中显示结果?
- html - CSS inline-block 场景 - 全部折叠或全部折叠
- javascript - 修改 JavaScript 原始类型的最佳实践