假设有一个线程,其中一个简单的服务器接受连接,另一个线程与客户端接受。
let () =
let sock = create_socket () in
let threads = Lwt.join [create_server sock; sock_read sock] in
Lwt_main.run threads
我试着写这样的客户端:
let sock_recv sock maxlen =
let str = Bytes.create maxlen in
let recvlen = Lwt_unix.recv sock str 0 maxlen [] in
String.sub str 0 recvlen
let sock_read sock =
let answer = sock_recv sock 512 in
Lwt_io.write_line Lwt_io.stdout answer
我有一个错误说:
File "lwt_server.ml", line 38, characters 19-26:
Error: This expression has type int Lwt.t
but an expression was expected of type int
与此相关:String.sub str 0 recvlen
回答这个问题(Working with ocaml Lwt sockets)我理解为了获得int
值,我必须创建一个带有bind
函数或中缀运算符的线程{ {1}}后跟一个匿名函数。但我所有的尝试都失败了。
那么如何在Lwt线程中读取套接字。
答案 0 :(得分:1)
您的sock_recv
和sock_read
函数应以这种方式编写:
let sock_recv sock maxlen =
let str = Bytes.create maxlen in
Lwt_unix.recv sock str 0 maxlen [] >>= fun recvlen ->
Lwt.return (String.sub str 0 recvlen)
let sock_read sock =
sock_recv sock 512 >>= fun answer ->
Lwt_io.write_line Lwt_io.stdout answer
即,当let x = foo in
返回Lwt值时,您将foo >>= fun x ->
的出现次序替换为foo
。但>>=
的右侧也必须返回Lwt值(因此Lwt.return
中的sock_recv
调用。)