term_to_binary 的字符串版本

发布于 2024-09-28 04:34:03 字数 300 浏览 9 评论 0原文

我正在尝试编写一个简单的服务器,通过 tcp 与客户端通信。我让它发送消息很好,但现在我希望它将消息解释为 Erlang 数据类型。例如,假设它类似于 HTTP(事实并非如此),并且我想从客户端发送 {get, "/foo.html"} 并让服务器将其解释为包含原子的元组和一个列表,而不仅仅是一个大列表或二进制文件。

我可能最终会使用 term_to_binarybinary_to_term,但是调试基于文本的协议要容易得多,因此我希望找到一个更适合列表的版本。难道有人躲在某处吗?

I'm trying to write a simple server that talks to clients via tcp. I have it sending messages around just fine, but now I want it to interpret the messages as Erlang data types. For example, pretend it's HTTP-like (it's not) and that I want to send from the client {get, "/foo.html"} and have the server interpret that as a tuple containing an atom and a list, instead of just a big list or binary.

I will probably end up using term_to_binary and binary_to_term, but debugging text-based protocols is so much easier that I was hoping to find a more list-friendly version. Is there one hiding somewhere?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

乖乖公主 2024-10-05 04:34:03

您可以通过以下方式将字符串解析为表达式(类似于 file:consult):(

% InputString = "...",
{ok, Scanned, _} = erl_scan:string(InputString),
{ok, Exprs} = erl_parse:parse_exprs(Scanned),
{value, ParsedValue, _} = erl_eval:exprs(Exprs, [])

请参阅 http ://www.trapexit.org/String_Eval

您应该能够使用 io_lib:format 使用 ~w~p 格式代码,例如 io_lib:format("~w", [{get, "/foo.html"}])

我认为这不会很快,所以如果性能是一个问题,你可能不应该使用这样的字符串。

另请注意,这可能是不安全的,因为您正在评估任意表达式 - 如果您走这条路,您可能应该对中间输出进行一些检查。我建议查看 erl_parse:parse_exprs 的结果,以确保它包含您感兴趣的格式(即,它始终是 {atom(), list()} 的元组)没有嵌入函数调用。您应该能够通过模式匹配来做到这一点。

You can parse a string as an expression (similar to file:consult) via:

% InputString = "...",
{ok, Scanned, _} = erl_scan:string(InputString),
{ok, Exprs} = erl_parse:parse_exprs(Scanned),
{value, ParsedValue, _} = erl_eval:exprs(Exprs, [])

(See http://www.trapexit.org/String_Eval)

You should be able to use io_lib:format to convert an expression to a string using the ~w or ~p format codes, such as io_lib:format("~w", [{get, "/foo.html"}]).

I don't think this will be very fast, so if performance is an issue you should probably not use strings like this.

Also note that this is potentially unsafe since you're evaluating arbitrary expressions -- if you go this route, you should probably do some checks on the intermediate output. I'd suggest looking at the result of erl_parse:parse_exprs to make sure it contains the formats you're interested in (i.e., it's always a tuple of {atom(), list()}) with no embedded function calls. You should be able to do this via pattern matching.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文