Reputation: 13
when i send data:"hello world" from c#-Part ,i received the data and put it to the test_out.txt,in which i found "hello world".should it be this without function binary_to_term? and then of course i got error :tcp_closed and a bit of gibberish in client. ---->thanks
[server]erlang-socket-code:
loop(Socket) ->
receive
{tcp,Socket,Bin} ->
io:format("server received binary = ~p~n",[Bin]),
file:write_file("test_out.txt", Bin),
B="welcome to unity3d:",
Response=[B | Bin],
io:format("server replying = ~p~n",[Response]),
gen_tcp:send(Socket,term_to_binary(Response)),
[client]c#-sockets-code
TcpClient client = new TcpClient("127.0.0.1", port);
byte[] data = System.Text.Encoding.UTF8.GetBytes(str);
NetworkStream stream = client.GetStream();
stream.Write(data, 0, data.Length);
Upvotes: 0
Views: 199
Reputation: 9289
You don't have to use binary_to_term
before writing it to file. Binary is sequence of bytes, so writing it to file works perfectly fine.
binary_to_term
is used, when you want to send complex Erlang terms through the network. It adds additional information.
1> String = "Hello". #Five letter string
"Hello"
2> Bin = term_to_binary(String). #Encode it with term_to_binary
<<131,107,0,5,72,101,108,108,111>> #9 bytes! You get info, that it is a list and it is of length 5
3> io:format("~s~n", [Bin]). #print the binary as it would appear in file
k^@^EHello
ok
If you want to send string, that you will write to file, you can simply use binaries, you don't have to convert it to lists or other Erlang terms.
In Erlang socket belongs to the process, that created it. If your process ended - the socket is closed. You either didn't call loop
recursively or the process crashed.
Upvotes: 1