package ws-server

  1. Overview
  2. Docs
WebSocket server

Install

Dune Dependency

Authors

Maintainers

Sources

0.1.tar.gz
md5=178fac2ab1b9a2cabe358a695282f4d2
sha512=77585a539320ef8a71f4d25f825ac84432934c49e6d4b7ae4f90ad4960aa44c31ceea8fe52c123364de937d3cb490ccd564d131f02b7eaca9f42795b86a1c70d

Description

Published: 06 Aug 2020

README

ws-server

Library for simple WebSocket servers (wrapper for ocaml-websocket).

Example

let string_of_client client =
  client |> Ws.Client.id |> Ws.Client.Id.to_int |> string_of_int

let server = Ws.Server.create ~port:3000

let on_connect client =
  Ws.Client.send client {|Commands:
/msg [user] [message]
/list
/quit|}

let handler client message =
  match String.split_on_char ' ' message with
  | [ "/list" ] ->
      let online =
        Ws.Server.clients server |> List.map string_of_client
        |> String.concat "\n"
      in
      Ws.Client.send client ("Online:\n" ^ online)
  | [ "/quit" ] -> Ws.Server.close server client
  | "/msg" :: user :: content -> (
      let target =
        match int_of_string_opt user with
        | Some n -> Ws.(Server.get server (Client.Id.of_int n))
        | None -> None
      in
      match target with
      | None -> Ws.Client.send client "No user with that ID exists"
      | Some target ->
          Ws.Client.send target
            (Printf.sprintf "Message from %s: %s" (string_of_client client)
               (String.concat " " content)) )
  | broadcast_message ->
      Ws.Server.broadcast_to_others server client
        (Printf.sprintf "%s: %s" (string_of_client client)
           (String.concat " " broadcast_message))

let () = Lwt_main.run (Ws.Server.run ~on_connect server handler)

Dependencies (4)

  1. websocket-lwt-unix
  2. lwt_ppx
  3. dune >= "2.0"
  4. ocaml >= "4.06"

Dev Dependencies

None

Used by

None

Conflicts

None

OCaml

Innovation. Community. Security.