term_to_binary 的字符串版本
我正在尝试编写一个简单的服务器,通过 tcp 与客户端通信。我让它发送消息很好,但现在我希望它将消息解释为 Erlang 数据类型。例如,假设它类似于 HTTP(事实并非如此),并且我想从客户端发送 {get, "/foo.html"}
并让服务器将其解释为包含原子的元组和一个列表,而不仅仅是一个大列表或二进制文件。
我可能最终会使用 term_to_binary
和 binary_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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以通过以下方式将字符串解析为表达式(类似于
file:consult
):(请参阅 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:(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 asio_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.