【问题标题】:"Bin" problems about receive {tcp,Socket,Bin} in communication between c# and erlangc#与erlang通信中关于receive {tcp,Socket,Bin}的“Bin”问题
【发布时间】:2014-10-28 19:03:12
【问题描述】:

当我从 c#-Part 发送数据:“hello world”时,我收到了数据并将其放入 test_out.txt,我在其中找到了“hello world”。应该是没有函数 binary_to_term 的吗?然后当然我得到了错误:tcp_closed 和客户端中的一些乱码。 ---->谢谢

[服务器]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)),

[客户端]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);

【问题讨论】:

  • 明白了!我从 c#:TcpClient 发送了错误的数据,顺便说一句,我仍然想知道 test_out.txt 是如何得到字符串的:“hello world”
  • 使用被动模式时:{avtive,false} and gen_tcp:recv/2, 1+1=2;当使用 {avtive ,true} 和 {tcp,sock,bin} 时,*&?·!

标签: c# sockets erlang


【解决方案1】:

在将其写入文件之前,您不必使用binary_to_term。二进制是字节序列,因此将其写入文件非常有效。

binary_to_term 用于通过网络发送复杂的 Erlang 术语。它添加了额外的信息。

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                        

如果你想发送字符串,你将写入文件,你可以简单地使用二进制文件,你不必将它转换为列表或其他 Erlang 术语。

在 Erlang 中,套接字属于创建它的进程。如果您的进程结束 - 套接字已关闭。您要么没有递归调用loop,要么进程崩溃了。

【讨论】:

  • 谢谢@tkowal.data 是二进制样式或字符串样式的数据。我从 c#-code 发送的二进制数据在服务器接收时缺少附加信息
  • @brushli 如果您想将数据用作 Erlang 术语(例如,当您通过 TCP 从 Erlang 节点向另一个 Erlang 节点发送元组时),则仅需要额外的数据。
猜你喜欢
  • 2011-09-25
  • 2019-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-10
  • 2015-05-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多