lwt-websocketというライブラリを公開しました。
酉打ち麻雀を開発するにあたって作ったものです。
クライアント側とサーバー側の両方で使え、ハンドシェイク後の通信チャネルを簡単に作成できます。
使い方はexampleのclient.mlとserver.mlを見ると早いですが、クライアント側とサーバー側についてそれぞれ大雑把に説明します。
抜粋ですが、クライアント側はこんな感じで、connectからchannelを作成します。
let host = "127.0.0.1" let port = 8080 let sec_socket_key = "aaa" let ping_test = Lwt_websocket.Channel.connect host port ~sec_socket_key >>= fun channel -> channel#write_ping_frame >>= fun () -> channel#read_frame >>= fun frame -> match frame with | Lwt_websocket.Frame.PongFrame(text) -> print_endline "pong received!"; return () | _ -> return () let () = Lwt_main.run pong_test
でもって、サーバー側は大体こんな感じで、acceptからchannelを作成します。
let rec accept_client sock_listen = Lwt_websocket.Channel.accept sock_listen >>= fun (addr, channel) -> handle_client channel and handle_client channel = match channel#read_frame with | Lwt_websocket.Frame.PingFrame(text) -> channel#write_pong_frame >>= fun () -> handle_client channel | _ -> return ()
ちなみにlwtというのは、ocamlの軽量スレッドライブラリのことです。
詳しい説明は本家のページのpdfを読むのが手っ取り早いです。
websocketのプロトコルですが、一応現在の最新っぽいやつを使ってgoogle chromeではちゃんと動いてます(他の環境では試してません)。