Support mulitplexing multiple clients
Anirudh Oppiliappan x@icyphox.sh
Sun, 26 Jul 2020 22:39:56 +0530
1 files changed,
34 insertions(+),
20 deletions(-)
jump to
M
src/wsabi.nim
→
src/wsabi.nim
@@ -11,24 +11,34 @@ json,
uri +# var +# server = newAsyncHttpServer() +# remote: WebSocket +# client: WebSocket +# clients: newSeq[WebSocket]() + +type + Client = object + ws: WebSocket + remote: WebSocket + var server = newAsyncHttpServer() - remote: WebSocket - client: WebSocket - clients: seq[WebSocket] + client: Client + clients = newSeq[Client]() -proc connectRemote(host: string) {.async.} = - remote = await newWebSocket(host, protocol = "xmpp") - let - (address, port) = remote.tcpSocket.getPeerAddr() - echo fmt"connected to {address}:{port.int}" +# proc connectRemote(remote: WebSocket, host: string) {.async.} = +# remote = await newWebSocket(host, protocol = "xmpp") +# let (address, port) = remote.tcpSocket.getPeerAddr() +# echo fmt"connected to {address}:{port.int}" -proc commRemoteClient() {.async.} = +proc commRemoteClient(c: Client) {.async.} = ## Fetch from remote and send to client - while remote.readyState == Open: - var data = await remote.receiveStrPacket() + while c.remote.readyState == Open: + echo "yes open" + var data = await c.remote.receiveStrPacket() echo "from remote: ", data - await client.send(data) + await c.ws.send(data proc localServer(req: Request) {.async, gcsafe.} = ## Listen on localhost:PORT/ws@@ -40,17 +50,24 @@ let bits = parseUri(remoteHost[0])
newreq.headers["host"] = @[fmt"{bits.hostname}:{bits.port}"] newreq.headers["hostname"] = @[bits.hostname] - client = await newWebSocket(newreq, protocol = "xmpp") + client.ws = await newWebSocket(newreq, protocol = "xmpp") + echo "connecting to remote host..." + client.remote = await newWebSocket(remoteHost[0], protocol = "xmpp") + let (address, port) = client.remote.tcpSocket.getPeerAddr() + echo fmt"connected to {address}:{port.int}" + clients.add client try: - while client.readyState == Open: + while client.ws.readyState == Open: # TODO: don't hardcode these replacements var - packet = await client.receiveStrPacket() + packet = await client.ws.receiveStrPacket() repacket = packet.replace("127.0.0.1", by=bits.hostname) echo "from local: " & repacket - await remote.send(repacket) + await client.remote.send(repacket) + echo "sent local packet" + asyncCheck commRemoteClient(client) except WebSocketError: echo "client closed socket: ", getCurrentExceptionMsg()@@ -113,14 +130,11 @@ let r = %*{"status": "error", "msg": e.msg}
await req.makeResponse(Http500, $r) - when isMainModule: parseArgs() - echo "connecting to remote host..." - waitFor connectRemote(remoteHost[0]) echo fmt"local server running at ws://127.0.0.1:{localPort}/ws" asyncCheck server.serve(Port(localPort), localServer) - asyncCheck commRemoteClient() + echo "calling commRemoteClient" runForever()