2016-09-16 64 views
0

假設有一個線程與一個簡單的服務器接受連接和另一個線程與客戶端。OCaml:如何讀取一個Lwt線程內的套接字

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函數或中綴運算符>>=後跟一個匿名函數。但我所有的嘗試都慘敗了。

那我該如何在Lwt線程中讀取套接字。

回答

1

sock_recvsock_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 

即,您可以通過foo >>= fun x ->取代let x = foo in出現時foo返回LWT值。但是>>=的右側也必須返回一個Lwt值(因此調用Lwt.returnsock_recv)。