2014-09-25 68 views
3

我正在嘗試構建一個Lwt循環,它會將幀推送到WebSocket,等待響應,將其打印到屏幕上,等待60秒,然後再次重複該過程。我已經能夠獲得編譯的東西,但我沒有100%的權利。第一次通過循環一切正常,然後每次我收到錯誤消息「無效的UTF8數據」。我必須在我的Lwt循環或我對Websocket協議的理解中出現錯誤。我的代碼:OCaml websocket「無效的UTF8數據」

#require "websocket";; 
#require "lwt";; 
#require "lwt.syntax";; 

open Lwt 

(* Set up the websocket uri address *) 
let ws_addr = Uri.of_string "websocket_address" 

(* Set up the websocket connection *) 
let ws_conn = Websocket.open_connection ws_addr 

(* Set up a frame *) 
let ws_frame = Websocket.Frame.of_string "json_string_to_server" 

(* push function *) 
let push frame() = 
    ws_conn 
    >>= fun (_, ws_pushfun) -> 
    ws_pushfun (Some frame); 
    Lwt.return() 

(* get stream element and print to screen *) 
let get_element() = 
    let print_reply (x : Websocket.Frame.t) = 
    let s = Websocket.Frame.content x in 
    Lwt_io.print s; Lwt_io.flush Lwt_io.stdout; 
    in 
    ws_conn 
    >>= fun(ws_stream, _) -> 
     Lwt_stream.next ws_stream 
     >>= print_reply 

let rec main() = 
    Lwt_unix.sleep 60.0 
    >>= (push ws_frame) 
    >>= get_element 
    >>= main 

Lwt_main.run(main()) 

回答

1

我不確定你的代碼特別不正確。它甚至不會在我的系統上編譯。看起來你是在頂層實驗它並創建了一些奇怪的上下文。我用更簡潔的方式重寫了你的代碼。首先,我傳遞給函數的一個連接,以便它更清晰,你的函數做什麼。此外,一次又一次地等待同一個線程並不是一個好主意。這不是如何做的是Lwt。

open Lwt 

(* Set up the websocket uri address *) 
let ws_addr = Uri.of_string "websocket_address" 

(* Set up a frame *) 
let ws_frame = Websocket.Frame.of_string "json_string_to_server" 

(* push function *) 
let push (_,push) frame = 
    push (Some frame); 
    return_unit 


(* get stream element and print to screen *) 
let get_element (stream,_) = 
    let print_reply (x : Websocket.Frame.t) = 
    let s = Websocket.Frame.content x in 
    Lwt_io.printlf "%s%!" s in 
    Lwt_stream.next stream 
    >>= print_reply 

let rec main conn : unit t = 
    Lwt_unix.sleep 60.0 
    >>= fun() -> push conn ws_frame 
    >>= fun() -> get_element conn 
    >>= fun() -> main conn 

let() = Lwt_main.run (
    Websocket.open_connection ws_addr >>= main) 
+0

我試過你的代碼,並遇到同樣的問題。我第一次得到結果,然後在第一次運行main後收到「無效的UTF8數據」錯誤。我已經在多個websockets上嘗試了我的版本和您的版本,以確保它不是特定服務器的問題。 (注意:我必須刪除代碼中的類型簽名才能編譯它。) – Thomas 2014-10-02 00:50:39

+0

好的,看起來問題不在代碼中。也許執行不完整。我建議你嘗試一下websocket庫中的示例程序https://github.com/vbmithr/ocaml-websocket/blob/master/tests/wscat.ml – ivg 2014-10-02 01:36:10

+0

有服務器和客戶端實現,你可以啓動一個服務器和檢查,是否可以與您的客戶進行通信。接下來,您可以使用他們的客戶端與您的服務器進行通話等。 – ivg 2014-10-02 01:37:14