1

我有一个客户端和一个服务器,我使用客户端发送一个字符串,例如"Hello"它在服务器端显示为<<"Hello">>. 有没有办法简单地转换<<"Hello">>"Hello"? 我尝试使用,

String = io_lib:format("~p",[StringIn]),
            lists:flatten(String),

但这使得格式<<"Hello">>变成了[[60,60,"\"Hello\"",62,62]]......

顺便说一下代码:

-module(ss1).
-compile(export_all).
-import(lists, [reverse/1]).

client() ->
    {ok, Socket} =  gen_tcp:connect("localhost", 2345,[binary, {packet, 4}]),
    ok = gen_tcp:send(Socket, "Hello"),
    receive
    {tcp,Socket,String} ->
        io:format("Client received = ~p~n",[String]),       
        io:format("Client result = ~p~n",[String]),
        gen_tcp:close(Socket)
    end.

server() ->
    {ok, Listen} = gen_tcp:listen(2345, [binary, {packet, 4},  {reuseaddr, true}, {active, true}]),
    {ok, Socket} = gen_tcp:accept(Listen),
    gen_tcp:close(Listen),  
    loop(Socket).

loop(Socket) ->
    receive
    {tcp,Socket,String} ->      
        io:format("Server received String = ~p~n",[String]),            
        io:format("Server replying String = ~p~n",[String]),
        gen_tcp:send(Socket, String), 
        loop(Socket);
    {tcp_closed, Socket} ->
        io:format("Server socket closed~n")
    end.
4

3 回答 3

5

原因是这一行:

{ok, Listen} = gen_tcp:listen(2345, [binary, {packet, 4},  {reuseaddr, true}, {active, true}]),

具体来说,原子binary在选项中传递。如果你通过list,你会得到一个普通的字符串。请参阅. _gen_tcp:listen/2

以下代码不起作用的原因:

String = io_lib:format("~p",[StringIn]),
lists:flatten(String), ...

lists:flatten/1实际上并没有改变 String吗?它返回一个新列表,该列表是展平其参数的结果。这会奏效:

lists:flatten(io_lib:format("~p", [StringIn])).
于 2013-03-20T10:53:46.513 回答
3

您可以使用 erlang 模块中的函数 - binary_to_list。

  Eshell V5.9.1  (abort with ^G)

1> B = <<"Hello">>.
<<"Hello">>
2> erlang:binary_to_list(B).
"Hello"
3> 
于 2013-03-20T01:05:54.553 回答
2

如果您只想使用io:formator打印二进制文件io_lib:format,则可以使用~s格式说明符:

1> MyBinary = <<"Hello">>.
<<"Hello">>
2> io:format("MyBinary is '~s'~n", [MyBinary]).
MyBinary is 'Hello'
ok
于 2013-03-20T11:19:34.903 回答