'gRPC / C++ - How to store server streaming RPC's stream for later use

What I want to achieve is to basically initiate messages from the server to the client. So basically my idea is I get the client to firstly trigger unary call which expect return of stream aka server streaming rpc.

I have this:

service Player {
    rpc PlayerSpawned(Empty) returns (stream CharacterShortData) {}
}

Here is my C++ code:

namespace Vibranium{
    class PlayerService final : public Vibranium::Protobuffers::Player::Service {
    private:
        typedef ::grpc::ServerWriter< Vibranium::Protobuffers::CharacterShortData>* PlayerSpawnedEvent;
        PlayerSpawnedEvent _playerSpawnedWritter;
    public:
        grpc::Status PlayerSpawned(::grpc::ServerContext* context, const Vibranium::Protobuffers::Empty* request, ::grpc::ServerWriter<Vibranium::Protobuffers::CharacterShortData>* writer) override;
        void PlayerSpawned(Vibranium::Protobuffers::CharacterShortData const & character_short_data);
        static PlayerService* Instance();
    };
}
    
#define sAuthorativePlayerService PlayerService::Instance()

Here is my implementation and how I try to store the stream for later use:

grpc::Status Vibranium::PlayerService::PlayerSpawned(::grpc::ServerContext *context, const Vibranium::Protobuffers::Empty *request,
                                              ::grpc::ServerWriter<Vibranium::Protobuffers::CharacterShortData> *writer)
{
    _playerSpawnedWritter = writer;
    return Status::OK;
}
void Vibranium::PlayerService::PlayerSpawned(const Vibranium::Protobuffers::CharacterShortData &character_short_data)
{
    _playerSpawnedWritter->Write(character_short_data);
}

However this does not work and I don't know why. Every time return Status::OK; deletes the pointer of writer which makes _playerSpawnedWritter invalid.

So every time I call PlayerSpawned I get a crash which is normal, because _playerSpawnedWritter is null.

So basically I can't store the stream. Is there any way I can keep the stream open and stored so later I can send additional messages specifically triggered from the server?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source