首页 > 解决方案 > 如何避免服务器(使用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()

标签: pythonpython-3.xwebsocketsupervisord

解决方案


推荐阅读