ws

Simple WebSocket library for nim.

Readme

Simple WebSocket library for nim.

Example Echo Server:

Example echo server, will repeat what you send it:

import ws, asyncdispatch, asynchttpserver

var server = newAsyncHttpServer()
proc cb(req: Request) {.async.} =
  if req.url.path == "/ws":
    var ws = await newWebsocket(req)
    await ws.sendPacket("Welcome to simple echo server")
    while ws.readyState == Open:
      let packet = await ws.receiveStrPacket()
      await ws.sendPacket(packet)
  await req.respond(Http200, "Hello World")

waitFor server.serve(Port(9001), cb)
ws = new WebSocket("ws://localhost:9001/ws")
ws.send("hi")

alt text

Example Chat Server:

Example chart server, will send what you send to connected all clients.

var connections = newSeq[WebSocket]()

proc cb(req: Request) {.async, gcsafe.} =
  if req.url.path == "/ws":
    try:
      var ws = await newWebsocket(req)
      connections.add ws
      await ws.sendPacket("Welcome to simple chat server")
      while ws.readyState == Open:
        let packet = await ws.receiveStrPacket()
        for other in connections:
          if other.readyState == Open:
            asyncCheck other.sendPacket(packet)
    except IOError:
      echo "socket closed"
  await req.respond(Http200, "Hello World")

var server = newAsyncHttpServer()
waitFor server.serve(Port(9001), cb)

In one tab:

ws = new WebSocket("ws://localhost:9001/ws")
ws.send("How are you?")

Other tab:

ws = new WebSocket("ws://localhost:9001/ws")
ws.send("Good, you?")
Need help? Read Nimble
Author:
treeform
No tagged versions available
License: MIT

Project website Hosted docs