all repos — wsabi @ 9066bd7031c6e80bfde3ac25ae3151d6b602186c

websocket proxy that sends stats to statsd

Init
Anirudh Oppiliappan x@icyphox.sh
Thu, 16 Jul 2020 21:05:47 +0530
commit

9066bd7031c6e80bfde3ac25ae3151d6b602186c

3 files changed, 94 insertions(+), 0 deletions(-)

jump to
A .gitignore

@@ -0,0 +1,1 @@

+wsabi
A src/wsabi.nim

@@ -0,0 +1,79 @@

+import asyncnet, asyncdispatch +import wsabi/utils + +type + Server = ref object + socket: AsyncSocket + clients: seq[Client] + + Client = ref object + socket: AsyncSocket + netAddr: string + id: int + connected: bool + +proc `$`(client: Client): string = + $client.id & "(" & client.netAddr & ")" + +proc newServer(): Server = + Server(socket: newAsyncSocket(), clients: @[]) + +proc sendRemote(remote: AsyncSocket, line: string) {.async.} = + await remote.send(line & "\c\L") + let msg = await remote.recv(10000) + if msg.len == 0: + echo("remote closed connection") + remote.close() + quit 0 + else: + echo msg + +proc processMsgs( + server: Server, client: Client, + remote: AsyncSocket + ) {.async.} = + while true: + let line = await client.socket.recvLine() + + if line.len == 0: + echo(client, " disconnected!") + client.connected = false + + client.socket.close() + return + + echo(client, "sent: ", line) + asyncCheck sendRemote(remote, line) + +proc loop(server: Server, port = 6000) {.async.} = + server.socket.bindAddr(port.Port) + echo("server initialised!") + server.socket.listen() + echo("listening on localhost:", port) + let remote = newAsyncSocket() + await remote.connect("example.com", 80.Port) + echo("connecting to remote... ") + echo("connected to remote:", getPeerAddr(remote)) + + while true: + let (netAddr, clientSocket) = await server.socket.acceptAddr() + echo("accepted connection from ", netAddr) + + let client = Client( + socket: clientSocket, + netAddr: netAddr, + id: server.clients.len, + connected: true + ) + server.clients.add(client) + asyncCheck processMsgs(server, client, remote) + +when isMainModule: + setControlCHook(handleCtrlC) + var server = newServer() + try: + waitFor loop(server) + except EKeyboardInterrupt: + echo("interrupted! closing sockets...") + server.socket.close() + quit 0
A wsabi.nimble

@@ -0,0 +1,14 @@

+# Package + +version = "0.1.0" +author = "Anirudh Oppiliappan" +description = "Load balance, monitor and failover Openfire servers" +license = "MIT" +srcDir = "src" +bin = @["wsabi"] + + + +# Dependencies + +requires "nim >= 1.0"