Search code examples
tcperlangerlang-otpgen-tcp

sending message over a socket using gen_tcp:send/2


How to send a message of the form [Integer, String] in erlang using gen_tcp.

Eg: I am looking to send messages of the form [25, "Hello"] or [50, "Hi"] over a socket using gen_tcp:send/2.

I tried to do [ID | Msg] but that doesn't help. Thanks


Solution

  • In Erlang, a string is just a list of Integers, so the list [25, "Hello"] is actually represented like [25, [72,101,108,108,111]]

    The question remains, how to send that information over a Socket in Erlang.

    According to the documentation, in Erlang you can send the data as binary or as a list, which you can set either as {mode, binary} or {mode, list} when you create the Socket.

    In the case that you are working with binary data (which is advice since sending and receiving binaries is faster than lists), you can do something like:

    {ok, Socket} = gen_tcp:connect(Host, Port, [{mode, binary}]).
    Data = list_to_binary([25, "Hello"]).
    gen_tcp:send(Socket, Data).
    

    Now, if you use your socket in list mode, you just send the list directly:

    {ok, Socket} = gen_tcp:connect(Host, Port, [{mode, binary}]).
    Data = [25, "Hello"].
    gen_tcp:send(Socket, Data).
    

    At the server side, if you receive the data in a Socket which is in list mode, you convert back to your original format with:

    [Integer|String] = ListReceived.
    

    If you receive the data in a Socket with binary mode, then you have to transform the data from a Binary to a List, like:

    [Integer|String] = binary_to_list(BinaryReceived).