[erlang-questions] 1st day of Erlang: what is wrong with this code

Jesper Louis Andersen jesper.louis.andersen@REDACTED
Sun Jul 12 12:03:10 CEST 2015


Hi!

Your problem hides itself in the original code:

-define(TCP_OPTIONS, [binary, {packet, 0}, {active, false}, {reuseaddr,
true}]).

This requests that the socket port is in 'binary' mode. This means that the
result of `gen_tcp:recv(Socket, 0)` is {ok, Data} is a binary, not a
string. One way around this is:

case gen_tcp:recv(Socket, 0) of
    {ok, Data} when is_binary(Data) ->
        String = binary_to_list(Data),
        gen_tcp:send(Socket, string:to_upper(Data)),
        loop(Socket);
    ...

This works for ASCII, but it fails blatantly for anything which is utf-8,
where the definition of uppercasing is less well understood. The reason you
can send a string() on a binary socket is that a string is a list of
code_points, and if the code points are all less than 128, then you have a
list of bytes. These are a subset of the iodata() type which
`gen_tcp:send/2` accepts.


On Sun, Jul 12, 2015 at 10:40 AM, avinash D'silva <evnix.com@REDACTED>
wrote:

> loop(Socket) ->
> case gen_tcp:recv(Socket, 0) of
> {ok, Data} ->
> gen_tcp:send(Socket, string:to_upper(Data)),
> loop(Socket);
> {error, closed} ->
> ok
> end.
>
> I get an error for string:to_upper()
>
> I am trying to create a simple echo server that converts text to upper
> case.
>
> original code: http://20bits.com/article/network-programming-in-erlang/
>
>
>
>
>
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions
>
>


-- 
J.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20150712/ce337fce/attachment.htm>


More information about the erlang-questions mailing list