简体   繁体   English

使用gen_tcp:send / 2通过套接字发送消息

[英]sending message over a socket using gen_tcp:send/2

How to send a message of the form [Integer, String] in erlang using gen_tcp. 如何使用gen_tcp以erlang格式发送[Integer,String]形式的消息。

Eg: I am looking to send messages of the form [25, "Hello"] or [50, "Hi"] over a socket using gen_tcp:send/2. 例如:我正在寻找使用gen_tcp:send / 2通过套接字发送[25,“ Hello”]或[50,“ Hi”]形式的消息。

I tried to do [ID | 我尝试做[ID | Msg] but that doesn't help. 讯息],但这无济于事。 Thanks 谢谢

In Erlang, a string is just a list of Integers, so the list [25, "Hello"] is actually represented like [25, [72,101,108,108,111]] 在Erlang中,字符串只是一个整数列表,因此列表[25, "Hello"]实际上表示为[25, [72,101,108,108,111]]

The question remains, how to send that information over a Socket in Erlang. 问题仍然是,如何通过Erlang中的Socket发送该信息。

According to the documentation , in Erlang you can send the data as binary or as a list , which you can set either as {mode, binary} or {mode, list} when you create the Socket. 根据文档 ,您可以在Erlang中以二进制列表的形式发送数据{mode, list}在创建Socket时可以将其设置为{mode, binary}{mode, list}

In the case that you are working with binary data (which is advice since sending and receiving binaries is faster than lists), you can do something like: 如果您使用的是二进制数据(这是建议,因为发送和接收二进制文件的速度比列表快),则可以执行以下操作:

{ok, Socket} = gen_tcp:connect(Host, Port, [{mode, binary}]).
Data = list_to_binary([25, "Hello"]).
gen_tcp:send(Socket, Data).

Now, if you use your socket in list mode, you just send the list directly: 现在,如果您以列表模式使用套接字,则只需直接发送列表:

{ok, Socket} = gen_tcp:connect(Host, Port, [{mode, binary}]).
Data = [25, "Hello"].
gen_tcp:send(Socket, Data).

At the server side, if you receive the data in a Socket which is in list mode, you convert back to your original format with: 在服务器端,如果您以列表模式在Socket中接收数据,则可以通过以下方式转换回原始格式:

[Integer|String] = ListReceived.

If you receive the data in a Socket with binary mode, then you have to transform the data from a Binary to a List, like: 如果以二进制模式在套接字中接收数据,则必须将数据从二进制转换为列表,例如:

[Integer|String] = binary_to_list(BinaryReceived).

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM