Question

I have a cowboy websocket server. Many clients send message over the websocket. I need to do processing on the message. I can do that in websocket_handle, However as it's realtime I would like to avoid it instead I want to send the message to a Global Process where all the processing can be done.

As Each cowboy has it's own process How to run a process where every user can send message and processing can be done in that process.

Was it helpful?

Solution

Just to clarify, each websocket connection will have its own erlang process in Cowboy, so messages from different websocket clients will be processed in different processes.

If you need to move the processing from the websocket you can simply start a new handler/server process when your app starts (e.g. when you start Cowboy) that listens for process commands and data. Sample processing code:

-module(my_processor).

-export([start/0]).

start() ->
    spawn(fun process_loop/0).

process_loop() ->
    receive
    {process_cmd, Data} ->
        process(Data)
    end,
    process_loop().

When you start it, also register the process with a global name. That way we can reference it from the websocket handlers later.

Pid=my_processor:start().
register(processor, Pid).

Now you can send the data from Cowboy's websocket_handle/3 function to the handling process:

websocket_handle(Data, Req, State) ->
         ...,
         processor ! {process_cmd, Data},
         ...,
         {ok,Req,State}.

Note that the my_processor process will handle the processing requests from all connections. If you want to have a separate process for each websocket connection you could start my_processor in Cowboy's websocket_init/3 function, store the Pid of the my_processorprocess in the State parameter returned from websocket_init and use that pid instead of the processor global name.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top