代码之家  ›  专栏  ›  技术社区  ›  hasherBaba

如何在WebSocket中接收新的响应?

  •  0
  • hasherBaba  · 技术社区  · 6 年前

    我有一个客户机模块:

    #!/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)
            greeting = await websocket.recv()
            print(greeting)
    
    asyncio.get_event_loop().run_until_complete(hello())
    

    服务器模块:

    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)
        while True:
            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)
            now = datetime.datetime.utcnow()
            diff = now - start_today
            request_match = start_match + diff
            print(diff)
            for post in db[collection].find():
                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"]
                        currDict_json = json.dumps(currDict, default=str)
                        print(currDict["tweet"])
                        await websocket.send(currDict_json)
                        await asyncio.sleep(1)
                        del currDict
    
    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)
    

    现在,问题是我只想将名称作为输入发送一次,并连续接收输出。 当我在客户机上写下这个时:

    while True:
       greeting = await.websocket.recv()
       print(greeting)
    

    同样的响应会一次又一次地返回。即使在服务器端,在我从数据库打印渲染结果的地方,我也在打印同一个文档。

    我完全不知道问题出在哪里?

    注意:我已经尝试运行Once-Run客户机模块,在那里我得到了完美的结果。只是我不得不一次又一次地给出相同的输入。我希望它是自动化的。

    1 回复  |  直到 6 年前
        1
  •  1
  •   furas    6 年前

    要连续获取数据,必须有人连续发送数据。

    如果有人连续发送数据,那么其他人必须连续获取数据。

    所以双方都需要循环。

    客户端-它连续循环发送数字。

    #!/usr/bin/env python
    import asyncio
    import websockets
    import time
    
    async def hello():
        async with websockets.connect(
                'ws://localhost:8769') as websocket:
    
            name = input("What's your name? ")
            await websocket.send(name)
    
            i = 0
            while True:
                print('send:', i)
    
                await websocket.send(str(i))
    
                time.sleep(2)
                i += 1
    
    try:
        asyncio.get_event_loop().run_until_complete(hello())
    except KeyboardInterrupt:
        print('KeyboardInterrupt')
    

    服务器-它连续循环接收数字

    import asyncio
    import websockets
    
    
    async def hello(websocket, path):
        entity_name = await websocket.recv()
        print('name:', entity_name)
    
        while True:
    
           data = await websocket.recv()
    
           print('recv:', data)
    
    
    try:
        print("Start entity server")
        start_server = websockets.serve(hello, '0.0.0.0', 8769)
        asyncio.get_event_loop().run_until_complete(start_server)
        asyncio.get_event_loop().run_forever()
    except KeyboardInterrupt: # keyboard need special except
        print("KeyboardInterrupt")
        start_server.ws_server.close() # solutin for [Errno 98]
    except Exception as ex:
        print(ex)