user2484294
user2484294

Reputation: 107

Receiving wrong data via TCP Erlang

I'm trying to receive some data via a TCP socket. When I run the code below I get the output: localhost^V^A^@, I am aware that you need to convert data if sending it using binary, but since I am sending a list I thought it would have been received the same? Why does the Host string show correctly but the other data doesn't?

Any help would be much appreciated, thanks.

cell_process(Port, X, Y)->
    Host = "localhost",
    Data = [Host,Port,X,Y],
    {ok, Socket} = gen_tcp:connect(Host, 22, 
                                 [list, {packet, 0}]),
    ok = gen_tcp:send(Socket, Data),
    ok = gen_tcp:close(Socket).


server_process(ClientList)->
{ok, Listening_socket} = gen_tcp:listen(22, [list, {packet, 0}, 
                                        {active, false}]),
{ok, Socket} = gen_tcp:accept(Listening_socket),
    case gen_tcp:recv(Socket,0) of
        {ok,Message}->
            io:fwrite(Message);
        {error,Why}->io:fwrite(Why)
    end.

Upvotes: 1

Views: 185

Answers (1)

拿小xi的铅笔
拿小xi的铅笔

Reputation: 74

Data = [Host,Port,X,Y]is a iolist,not a list.
gen_tcp:send will convert Data to [<<"localhost">>,<<22:8>>]

here is the doc of iolist:

iodata() = iolist() | binary()
iolist()     maybe_improper_list(char() | binary() | iolist(), binary() | [])
maybe_improper_list()     maybe_improper_list(any(), any())
byte()     0..255
char()     0..16#10ffffmaybe_improper_list(T)     maybe_improper_list(T, any())

Upvotes: 2

Related Questions