【问题标题】:Making socket communication using bin_prot使用 bin_prot 进行套接字通信
【发布时间】:2015-06-15 14:08:07
【问题描述】:

我想在 OCaml 中使用 bin_prot 进行 Socket 通信。但是,我找不到任何详细的解释或示例来做到这一点。我之前用其他方式做Socket通信,所以我知道它的流程。
OCaml中使用bin_prot进行Socket通信有很好的解释或者例子吗?

【问题讨论】:

    标签: sockets ocaml communication


    【解决方案1】:

    好吧,bin_prot 只是一个序列化协议,它不依赖于您用于传输层的任何内容。基本上,要将值序列化为字符串,您可以使用Binable.to_string 函数(或Binable.to_bigstring)。它接受一个打包的模块。例如,要序列化一组 int,请执行以下操作:

     let str = Binable.to_string (module Int.Set) mine_set; 
    

    其中mine_set 是整数集。

    如果您有实现 bin_prot 的任意类型,那么它的工作方式相同。一个例子是:

    module My_data = struct
      type t = int * string with bin_io
    end
    let str = Binable.to_string (module My_data) (42,"answer")
    

    【讨论】:

    • 谢谢。那么,如果我不知道我要序列化的数据的类型,我该怎么办呢?我的意思是程序let f x = let str = Binable.to_string (module ...) x in str。在这种情况下,我怎么知道 x 的类型?
    • s / x 类型 / x 的类型
    • 如果不知道类型,就不能用binprot序列化。 x 的类型等于 M 模块的 M.t 类型,它作为 to_string 函数的第一个参数传递,例如 (module M)。例如,如果你传递(module Int.Set),那么第二个参数的类型应该是Int.Set.t,等等
    • 我明白了。非常感谢。我可以在编译程序时制作模块M和类型M.t吗?我想在程序中写let f x = let str = Binable.to_string (module ...) x in str,所以x在编译时会得到一个具体的类型,例如int * int。我想如果我能做到,我可以在程序中写let f x = let str = Binable.to_string (module ...) x in str
    • 我的意思是在程序的某些地方使用了函数f。例如,let f x = let str = Binable.to_string (module ...) x in str in .... f (2, 2) ...。在这种情况下,x 在编译时获取类型int * int。我想在 x 获取类型 int * int 之后制作模块 M 和类型 M.t
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-26
    • 2021-11-26
    相关资源
    最近更新 更多