"일꾼이 일을 잘하려면 먼저 도구를 갈고 닦아야 한다." - 공자, 『논어』.
첫 장 > 프로그램 작성 > gRPC에서 서버-클라이언트 브로드캐스팅을 구현하는 방법은 무엇입니까?

gRPC에서 서버-클라이언트 브로드캐스팅을 구현하는 방법은 무엇입니까?

2024-11-05에 게시됨
검색:891

How to Implement Server to Client Broadcasting in gRPC?

gRPC에서 브로드캐스트: 서버-클라이언트 통신

gRPC 연결을 설정할 때 서버에서 서버로 이벤트나 업데이트를 브로드캐스트해야 하는 경우가 많습니다. 연결된 클라이언트. 이를 달성하기 위해 다양한 접근 방식을 사용할 수 있습니다.

스트림 관찰 가능

일반적인 접근 방식 중 하나는 서버 측 스트림을 활용하는 것입니다. 연결된 각 클라이언트는 서버와 함께 자체 스트림을 설정합니다. 그러나 다른 서버-클라이언트 스트림을 직접 구독하는 것은 불가능합니다.

장기 폴링

대체 옵션은 장기 폴링 접근 방식을 구현하는 것입니다. 여기에는 클라이언트가 정기적으로 서버를 지속적으로 폴링하여 새 업데이트를 확인하도록 하는 것이 포함됩니다. 업데이트를 받으면 클라이언트는 응답을 받고 다음 폴링 간격을 기다립니다.

구현 예

다음은 장기 폴링을 구현하는 방법의 예입니다. gRPC 사용:

서버측 코드

import threading

class UpdaterServer:
    def __init__(self):
        self.condition = threading.Condition()
        self.updates = []

    def post_update(self, update):
        with self.condition:
            self.updates.append(updates)
            self.condition.notify_all()

    def GetUpdates(self, req, context):
        with self.condition:
            while self.updates[req.last_received_update   1:] == []:
                self.condition.wait()
            new_updates = self.updates[req.last_received_update   1:]
            return GetUpdatesResponse(
                updates=new_updates,
                update_index=req.last_received_update   len(new_updates),
            )

클라이언트측 코드(별도 스레드)

from threading import Event

def handle_updates(updates):
    pass

event = Event()
request = GetUpdatesRequest(last_received_update=-1)

while not event.is_set():
    try:
        stub = UpdaterStub(channel)
        response = stub.GetUpdates(request, timeout=60*10)
        handle_updates(response.updates)
        request.last_received_update = response.update_index
    except grpc.FutureTimeoutError:
        pass

이 접근 방식을 구현하면 연결된 클라이언트가 서버에서 지속적으로 업데이트를 검색할 수 있습니다.

최신 튜토리얼 더>

부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.

Copyright© 2022 湘ICP备2022001581号-3