# Command Pattern via TCP

**URL:** <https://forum.elixirforum.com/t/command-pattern-via-tcp/42809>\
**Category:** Questions\
**Tags:** rpc, command-pattern\
**Created:** [October 2, 2021, 6:59pm UTC](https://forum.elixirforum.com/t/command-pattern-via-tcp/42809 "2021-10-02T18:59:20Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![smanza](https://forum.elixirforum.com/letter_avatar_proxy/v4/letter/s/3ec8ea/32.png) [@smanza](https://forum.elixirforum.com/u/smanza)\
**Post date:** [October 2, 2021, 7:33pm UTC](https://forum.elixirforum.com/t/command-pattern-via-tcp/42809/2 "2021-10-02T19:33:56Z")

</div>

I implementated a concept like this with tcp but I took another approach (without the polymerphism) .

By simply using the pattern matching , I have a module Message where there is a function encode , decode, and process.

The `encode` takes a message (struct) and serializes it by prepending a message which is then used to pattern match on the `decode` function.  
And then the `process` take message struct as parameter to perform the task for the command.

Example:

```elixir
defmodule Message do

  def encode(%MyMessage{}) do 
     <<0::8>>
  end

  def decode(<<0::8>>), do: %MyMessage{}

   def process(%MyMessage{}) do
       # Doing stuff
    end
end

```

And on the tcp handler:

```elixir
data_to_send = data_received
|> Message.decode()
|> Message.process()
|> Message.encode() # If you want to send a response

```

If it can help you 😉

---

_[View the full topic](https://forum.elixirforum.com/t/command-pattern-via-tcp/42809)._
