Skip to content

Instantly share code, notes, and snippets.

@beligante
Created October 29, 2022 16:37
Show Gist options
  • Save beligante/f715d3c8896df8b42d771f2b66106743 to your computer and use it in GitHub Desktop.
Save beligante/f715d3c8896df8b42d771f2b66106743 to your computer and use it in GitHub Desktop.
Mint example without Gun workaround
# CD to grpc/examples/route_guide
# mix deps.get
# iex -S mix
# Past this on your console
opts = [interceptors: [GRPC.Logger.Client], adapter: GRPC.Client.Adapters.Mint]
{:ok, channel} = GRPC.Stub.connect("localhost:10000", opts)
RouteGuide.Client.main(channel)
defmodule MyStreamHandlerProcess do
use GenServer
def receive_stream(grpc_stream, pid) do
{:ok, ex_stream} = GRPC.Stub.recv(grpc_stream) |> IO.inspect()
# async cause Stream.run() will block the code until the stream is done
Task.async(fn ->
ex_stream
|> Stream.each(fn resp ->
case resp do
{:ok, data} -> send(pid, {:elixir_grpc, {:data, data}})
_other -> send(pid, {:elixir_grpc, resp})
end
end)
|> Stream.run() # code will be blocked until the stream end
# send a message to tell the process that the stream has ended
send(pid, {:elixir_grpc, :done})
end)
end
def init(_) do
{:ok, nil}
end
def handle_info({:elixir_grpc, {:headers, headers}}, state) do
IO.inspect(headers, label: "headers:")
{:noreply, state}
end
def handle_info({:elixir_grpc, {:data, data}}, state) do
IO.inspect(data, label: "data:")
{:noreply, state}
end
def handle_info({:elixir_grpc, {:trailers, trailers}}, state) do
IO.inspect(trailers, label: "trailers:")
{:noreply, state}
end
def handle_info({:elixir_grpc, :done}, state) do
IO.inspect("done")
{:noreply, state}
end
def handle_info(msg, state) do
IO.inspect(msg, label: "Received unknown msg:")
{:noreply, state}
end
end
{:ok, pid} = GenServer.start_link(MyStreamHandlerProcess, nil)
opts = [interceptors: [GRPC.Logger.Client]]
GRPC.Stub.connect("localhost:10000", opts)
stream = channel |> Routeguide.RouteGuide.Stub.route_chat()
task = Task.async(fn ->
[
%{lat: 0, long: 1, msg: "First message"},
%{lat: 0, long: 2, msg: "Second message"},
%{lat: 0, long: 3, msg: "Third message"},
%{lat: 0, long: 1, msg: "Fourth message"},
%{lat: 0, long: 2, msg: "Fifth message"},
%{lat: 0, long: 3, msg: "Sixth message"}
]
|> Enum.map(fn %{lat: lat, long: long, msg: msg} ->
point = Routeguide.Point.new(latitude: lat, longitude: long)
Routeguide.RouteNote.new(location: point, message: msg)
end)
|> Enum.each(fn note ->
GRPC.Stub.send_request(stream, note, opts)
Process.sleep(1000)
end)
GRPC.Stub.end_stream(stream)
end)
MyStreamHandlerProcess.receive_stream(stream, pid)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment