Coder Social home page Coder Social logo

ws's People

Contributors

ba0f3 avatar erikwdev avatar tangdongle avatar treeform avatar vindaar avatar zedeus avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ws's Issues

Custom error types throwing "undeclared identifier" error when running examples from fresh nimble install on v0.4.3

Here is the code and the error message:

import asyncdispatch, asynchttpserver, ws

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.send("Welcome to simple chat server")
      while ws.readyState == Open:
        let packet = await ws.receiveStrPacket()
        echo "Received packet: " & packet
        for other in connections:
          if other.readyState == Open:
            asyncCheck other.send(packet)
    except WebSocketClosedError:
      echo "Socket closed. "
    except WebSocketProtocolMismatchError:
      echo "Socket tried to use an unknown protocol: ", getCurrentExceptionMsg()
    except WebSocketError:
      echo "Unexpected socket error: ", getCurrentExceptionMsg()
  await req.respond(Http200, "Hello World")

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

serve.nim(5, 25) template/generic instantiation of 'async' from here

serve.nim(17, 12) Error: undeclared identifier: 'WebSocketClosedError'

I thought that maybe the var ws = await newWebSocket(req) line might be causing issues since the package is named ws but changing the variable name produces the same results.

gcsafe error

Running example echo or chat server gives compiler error:

asyncmacro.nim(250,31) error: "cb (Async)' is not GC-safe as it accesses 'connections' which is a global GC'ed memory

Sending custom headers when opening a client connection

Hello,

I would have liked to send an authorization header when establishing a client connection but found no way to do so. I worked around this by making the authorization token a URL parameter, but it would have been nicer if it was a header. Maybe this can be included in a future API change.

pingLoop causes SEGVs

Hi,
I was trying to write code that will reconnect the websocket connection once it's broken for any reason, like this:

var csSock: WebSocket  # defined in some scope

proc setup(csSock: var WebSocket) =
  csSock = waitFor newWebSocket(CSURL)
  csSock.setupPings(15)

proc getMsg(csSock: var WebSocket): string = 
  try:
      result = waitFor csSock.receiveStrPacket
    except WebSocketError:
      csSock.setup

while true:
  discard getMsg()

I believe setupPings(15) proc will create a new async task that will periodically send pings to a given WebSocket. In case socket disconnection and a new socket created, the application will terminate with very unclear segmentation fault (attempt to read from nil). Perhaps the ping task is trying to access the memory address that was previously assigned to the old socket? Not sure, anyway commenting out the setupPings line solves this issue.

I'm not sure if this is a library fault or just me using this library in a wrong way but I'll be happy to provide more evidence on this behavior if needed.

Make ws compatible with Jester + HttpBeast

It seems like ws is not compatible with Jester when HttpBeast is used. The following code only compiles if I change line 7 in Jester/private/utils to useHttpBeast* = false:

import jester
import ws

routes:
  get "/ws": 
    var ws = await newWebSocket(request.getNativeReq)
    await ws.send("Welcome to simple echo server")
    while ws.readyState == Open:
      let packet = await ws.receiveStrPacket()
      await ws.send(packet)

Compiling with useHttpBeast turned on produces an error:

/Users/filipux/test.nim(6, 32) Error: type mismatch: got <Request>
but expected one of: 
proc newWebSocket(req: Request): Future[WebSocket]
  first type mismatch at position: 1
  required type for req: Request
  but expression 'getNativeReq(request)' is of type: Request```

Ws server protected by cloudflare vulnerable to simple attack

This code:

import asyncdispatch, asynchttpserver, ws

proc main() {.async.} =
  var ws = await newWebSocket("wss://cloudflare-protected-server.com")

  await ws.send(newString(1024*1024*1024*2))
  echo "sent"
  echo await ws.receiveStrPacket()

  ws.close()

waitFor main()

Will cause the server to allocate gigabytes of memory and stall filling the buffer with the empty data created in newString, cloudflare does not prevent this

client.close() crashes server process

I run the simple server code from README.md with a browser as the client. The client is able to connect correctly but when the client code calls ws.close() the server crashes. Am running the latest version of the package 0.4.0 and nim 1.0.4 on Ubuntu. What's the issue?

server can't keep websocket connection alive and won't send any data

I am struggling on this for more than a day and I can not figure out what's wrong.

My program runs multiple async proc's including a jester server with a ws endpoint;

  get "/ws":
    var ws = await newWebSocket(request)
    {.cast(gcsafe).}:
      connections.add ws
    while ws.readyState == Open:
      let packet = await ws.receiveStrPacket()
      echo packet
    resp "ok"

connections is a global sequence:

var connections = newSeq[WebSocket]()

I also have this proc that gets called from an async proc sometimes:

proc notifyClientConnection*(client: Client) {.async.} =
  for connection in connections:
    if connection.readyState == Open:
      await connection.send($client.id)

The problem is that nothing is being sent, despite the connection being open. Another issue is that the connection gets closed (after I try to send something for the first time in the session) without the client being notified that the connection got closed. I have no idea what's happening. There are no errors thrown on the client or the server. I think it must be a problem with the library?

Edit: I added another call to connection.send before the first one and now they both work. I restarted the websocket server and they both stopped worked. Added a third send call and they all started working again, of course until I restarted the server, it wont work until I edit that specific function and recompile the code.

Key not found: sec-websocket-protocol

I'm connecting to a remote websocket server, with the protocol xmpp. Here's what the proc definition looks like:

proc connectRemote(host: string) {.async.} =
  remote = await newWebSocket(host, protocol = "xmpp")
  let 
    hostPort = remote.tcpSocket.getPeerAddr()
    address = hostPort[0]
    port = hostPort[1].int
  echo fmt"connected to {address}:{port}"

And it errors while attempting to connect with

Exception message: key not found: sec-websocket-protocol
Exception type: [KeyError]

Alternate Opcodes?

Im probably being stupid here but how do i use alternate opcodes?
Im trying to send an opcode of 2 and ill need to send one of 13 later but its not allowing me to
Is it possible to make the function accept an integer for opcodes?

Closing Client Connection Exception

Running the server example, connecting with a websocket client then closing the client connection produced in the server: Error: unhandled exception: Socket got invalid frame, looking for Text or Binary [WebSocketError].

How to correct?

ws with JS backend?

Hi,

How do I compile the client example from the readme for Javascript:

var ws = await newWebSocket("ws://127.0.0.1:9001/ws")
echo await ws.receiveStrPacket()
await ws.send("Hi, how are you?")
echo await ws.receiveStrPacket()
ws.close()

?

Thanks

All exceptions are WebSocketError. More specific exceptions possible?

Hi!
I see that all exceptions being raised are just WebSocketError. It is hard to only except "Closed" exceptions in one way and other exceptions in their own ways.

Could we perhaps have something like WebSocketClosedError, WebSocketProtocolMismatchError, WebSocketHandshakeError and so on which could all be object of WebSocketError. This would ensure that scripts that already catch WebSocketError would still work (right?).

I might take a look tonight and see if I can submit a PR

ws breaks Nim CI

Ref nim-lang/Nim#18804

https://github.com/nim-lang/Nim/pull/18804/checks?check_run_id=3513974159

  Failure: reBuildFailed
  nimble test
    Verifying dependencies for [email protected]
    Compiling /Users/runner/work/Nim/Nim/pkgstemp/ws/tests/test (from package ws) using c backend
  /Users/runner/work/Nim/Nim/pkgstemp/ws/src/ws.nim(321, 48) template/generic instantiation of `async` from here
  /Users/runner/work/Nim/Nim/pkgstemp/ws/src/ws.nim(348, 32) Warning: conversion to enum with holes is unsafe: Opcode(b0 and 0x0000000F) [HoleEnumConv]
     Success: Execution finished
    Verifying dependencies for [email protected]
    Compiling /Users/runner/work/Nim/Nim/pkgstemp/ws/tests/test_404 (from package ws) using c backend
  /Users/runner/work/Nim/Nim/pkgstemp/ws/src/ws.nim(321, 48) template/generic instantiation of `async` from here
  /Users/runner/work/Nim/Nim/pkgstemp/ws/src/ws.nim(348, 32) Warning: conversion to enum with holes is unsafe: Opcode(b0 and 0x0000000F) [HoleEnumConv]
     Success: Execution finished
    Verifying dependencies for [email protected]
    Compiling /Users/runner/work/Nim/Nim/pkgstemp/ws/tests/test_disconnects (from package ws) using c backend
  /Users/runner/work/Nim/Nim/pkgstemp/ws/src/ws.nim(321, 48) template/generic instantiation of `async` from here
  /Users/runner/work/Nim/Nim/pkgstemp/ws/src/ws.nim(348, 32) Warning: conversion to enum with holes is unsafe: Opcode(b0 and 0x0000000F) [HoleEnumConv]
  /Users/runner/work/Nim/Nim/pkgstemp/ws/tests/test_disconnects.nim(14, 31) template/generic instantiation of `async` from here
  /Users/runner/work/Nim/Nim/lib/pure/asyncmacro.nim(200, 31) Warning: 'serverCbIter' is not GC-safe as it accesses 'curWs' which is a global using GC'ed memory [GcUnsafe2]
  gameLoop:0
  gameLoop:1
  (Text, "Welcome to simple echo server")
  reading...
  gameLoop:2
  gameLoop:3
  gameLoop:4
  (Close, "")
  serverCb exception:Socket closed
  clientLoop exception:Socket closed
  gameLoop:5
     Success: Execution finished
    Verifying dependencies for [email protected]
    Compiling /Users/runner/work/Nim/Nim/pkgstemp/ws/tests/test_httptowsendpoint (from package ws) using c backend
  /Users/runner/work/Nim/Nim/pkgstemp/ws/src/ws.nim(321, 48) template/generic instantiation of `async` from here
  /Users/runner/work/Nim/Nim/pkgstemp/ws/src/ws.nim(348, 32) Warning: conversion to enum with holes is unsafe: Opcode(b0 and 0x0000000F) [HoleEnumConv]
  success: got 404 because not /ws
  success: got 400 because made http call to /ws
     Success: Execution finished
    Verifying dependencies for [email protected]
    Compiling /Users/runner/work/Nim/Nim/pkgstemp/ws/tests/test_protocol (from package ws) using c backend
  /Users/runner/work/Nim/Nim/pkgstemp/ws/src/ws.nim(321, 48) template/generic instantiation of `async` from here
  /Users/runner/work/Nim/Nim/pkgstemp/ws/src/ws.nim(348, 32) Warning: conversion to enum with holes is unsafe: Opcode(b0 and 0x0000000F) [HoleEnumConv]
     Success: Execution finished
    Verifying dependencies for [email protected]
    Compiling /Users/runner/work/Nim/Nim/pkgstemp/ws/tests/test_protocol_arr (from package ws) using c backend
  /Users/runner/work/Nim/Nim/pkgstemp/ws/src/ws.nim(321, 48) template/generic instantiation of `async` from here
  /Users/runner/work/Nim/Nim/pkgstemp/ws/src/ws.nim(348, 32) Warning: conversion to enum with holes is unsafe: Opcode(b0 and 0x0000000F) [HoleEnumConv]
  /Users/runner/work/Nim/Nim/pkgstemp/ws/tests/test_protocol_arr.nim(32) test_protocol_arr
  /Users/runner/work/Nim/Nim/lib/pure/asyncdispatch.nim(1961) waitFor
  /Users/runner/work/Nim/Nim/lib/pure/asyncdispatch.nim(1653) poll
  /Users/runner/work/Nim/Nim/lib/pure/asyncdispatch.nim(1394) runOnce
  /Users/runner/work/Nim/Nim/lib/pure/asyncdispatch.nim(234) processPendingCallbacks
  /Users/runner/work/Nim/Nim/lib/pure/asyncmacro.nim(28) sendNimAsyncContinue
  /Users/runner/work/Nim/Nim/pkgstemp/ws/src/ws.nim(316) sendIter
  [[reraised from:
  /Users/runner/work/Nim/Nim/pkgstemp/ws/tests/test_protocol_arr.nim(32) test_protocol_arr
  /Users/runner/work/Nim/Nim/lib/pure/asyncdispatch.nim(1961) waitFor
  /Users/runner/work/Nim/Nim/lib/pure/asyncdispatch.nim(1653) poll
  /Users/runner/work/Nim/Nim/lib/pure/asyncdispatch.nim(1394) runOnce
  /Users/runner/work/Nim/Nim/lib/pure/asyncdispatch.nim(234) processPendingCallbacks
  /Users/runner/work/Nim/Nim/lib/pure/asyncmacro.nim(28) sendNimAsyncContinue
  /Users/runner/work/Nim/Nim/lib/system/excpt.nim(144) sendIter
  ]]
  [[reraised from:
  /Users/runner/work/Nim/Nim/pkgstemp/ws/tests/test_protocol_arr.nim(32) test_protocol_arr
  /Users/runner/work/Nim/Nim/lib/pure/asyncdispatch.nim(1961) waitFor
  /Users/runner/work/Nim/Nim/lib/pure/asyncdispatch.nim(1653) poll
  /Users/runner/work/Nim/Nim/lib/pure/asyncdispatch.nim(1394) runOnce
  /Users/runner/work/Nim/Nim/lib/pure/asyncdispatch.nim(234) processPendingCallbacks
  /Users/runner/work/Nim/Nim/lib/pure/asyncmacro.nim(28) closeNimAsyncContinue
  /Users/runner/work/Nim/Nim/lib/pure/asyncmacro.nim(131) closeIter
  /Users/runner/work/Nim/Nim/lib/pure/asyncfutures.nim(389) read
  ]]
  [[reraised from:
  /Users/runner/work/Nim/Nim/pkgstemp/ws/tests/test_protocol_arr.nim(32) test_protocol_arr
  /Users/runner/work/Nim/Nim/lib/pure/asyncdispatch.nim(1961) waitFor
  /Users/runner/work/Nim/Nim/lib/pure/asyncdispatch.nim(1653) poll
  /Users/runner/work/Nim/Nim/lib/pure/asyncdispatch.nim(1394) runOnce
  /Users/runner/work/Nim/Nim/lib/pure/asyncdispatch.nim(234) processPendingCallbacks
  /Users/runner/work/Nim/Nim/lib/pure/asyncfutures.nim(437) asyncCheckCallback
  ]]
  Error: unhandled exception: Failed to send data: Bad file descriptor
  Async traceback:
    /Users/runner/work/Nim/Nim/pkgstemp/ws/tests/test_protocol_arr.nim(32) test_protocol_arr
    /Users/runner/work/Nim/Nim/lib/pure/asyncdispatch.nim(1961)            waitFor
    /Users/runner/work/Nim/Nim/lib/pure/asyncdispatch.nim(1653)            poll
    /Users/runner/work/Nim/Nim/lib/pure/asyncdispatch.nim(1394)            runOnce
    /Users/runner/work/Nim/Nim/lib/pure/asyncdispatch.nim(234)             processPendingCallbacks
    /Users/runner/work/Nim/Nim/lib/pure/asyncmacro.nim(28)                 sendNimAsyncContinue
    /Users/runner/work/Nim/Nim/pkgstemp/ws/src/ws.nim(316)                 sendIter
    #[
      /Users/runner/work/Nim/Nim/pkgstemp/ws/tests/test_protocol_arr.nim(32) test_protocol_arr
      /Users/runner/work/Nim/Nim/lib/pure/asyncdispatch.nim(1961)            waitFor
      /Users/runner/work/Nim/Nim/lib/pure/asyncdispatch.nim(1653)            poll
      /Users/runner/work/Nim/Nim/lib/pure/asyncdispatch.nim(1394)            runOnce
      /Users/runner/work/Nim/Nim/lib/pure/asyncdispatch.nim(234)             processPendingCallbacks
      /Users/runner/work/Nim/Nim/lib/pure/asyncmacro.nim(28)                 sendNimAsyncContinue
      /Users/runner/work/Nim/Nim/lib/system/excpt.nim(144)                   sendIter
    ]#
    #[
      /Users/runner/work/Nim/Nim/pkgstemp/ws/tests/test_protocol_arr.nim(32) test_protocol_arr
      /Users/runner/work/Nim/Nim/lib/pure/asyncdispatch.nim(1961)            waitFor
      /Users/runner/work/Nim/Nim/lib/pure/asyncdispatch.nim(1653)            poll
      /Users/runner/work/Nim/Nim/lib/pure/asyncdispatch.nim(1394)            runOnce
      /Users/runner/work/Nim/Nim/lib/pure/asyncdispatch.nim(234)             processPendingCallbacks
      /Users/runner/work/Nim/Nim/lib/pure/asyncmacro.nim(28)                 closeNimAsyncContinue
      /Users/runner/work/Nim/Nim/lib/pure/asyncmacro.nim(131)                closeIter
      /Users/runner/work/Nim/Nim/lib/pure/asyncfutures.nim(389)              read
    ]#
  Exception message: Failed to send data: Bad file descriptor
   [WebSocketError]
  Error: execution of an external program failed: '/Users/runner/work/Nim/Nim/pkgstemp/ws/tests/test_protocol_arr '
         Tip: 6 messages have been suppressed, use --verbose to show them.
       Error: Execution failed with exit code 256
          ... Command: /Users/runner/work/Nim/Nim/bin/nim c --noNimblePath -d:NimblePkgVersion=0.4.4 --hints:off -r --path:. /Users/runner/work/Nim/Nim/pkgstemp/ws/tests/test_protocol_arr

Protocol for client

When using newWebSocket how are we meant to specify the protocol?

Here is a quick diff I cooked up to do it:

diff --git a/src/ws.nim b/src/ws.nim
index 83c04aa..77e4f8e 100644
--- a/src/ws.nim
+++ b/src/ws.nim
@@ -86,11 +86,12 @@ proc newWebSocket*(req: Request): Future[WebSocket] {.async.} =
   return ws
 
 
-proc newWebSocket*(url: string): Future[WebSocket] {.async.} =
+proc newWebSocket*(url: string, protocol = ""): Future[WebSocket] {.async.} =
   ## Creates a client
   var ws = WebSocket()
   ws.req = Request()
   ws.req.client = newAsyncSocket()
+  ws.protocol = protocol
 
   var uri = parseUri(url)
   var port = Port(9001)
@@ -114,6 +115,8 @@ proc newWebSocket*(url: string): Future[WebSocket] {.async.} =
     "Sec-WebSocket-Key": "JCSoP2Cyk0cHZkKAit5DjA==",
     "Sec-WebSocket-Extensions": "permessage-deflate; client_max_window_bits"
   })
+  if ws.protocol.len != 0:
+    client.headers["Sec-WebSocket-Protocol"] = ws.protocol
   var _ = await client.get(url)
   ws.req.client = client.getSocket()
 

Personally I would change this API:

  • newWebSocket should only initialise the object, it shouldn't perform any connections
  • a connect proc

Also I ran into other issues:

  • No PING/PONG handling in the client?

Exception: "WebSocket potocol missmatch"

I'm facing a issue with using ws to receive stream data from a websocket server, the server is established with json-rpc over websocket and I have no control over it. The basic data receiving logic is to connect to server and send subscription msg on a channel, then start a loop to receive stream data from server,

# subscribe to channel 
  await ws.send("""
{
  "jsonrpc": "2.0",
  "method": "add",
  "params": {
    "data": ["notify"],
    "entity": "subscriptions",
    "userEmail": "xxxxx",
    "authToken": "xxxxx",
    "project_uid": "xxxxx"
  },
  "id": 2
}
""")

  echo await ws.receiveStrPacket()
  # start receiving stream data
  while ws.readyState == Open:
    let packet = await ws.receiveStrPacket()
    echo packet
   
ws.close()
....

the code running without issue and can receive data normally, but sometimes it throw exception: "Exception message: WebSocket Potocol missmatch
Exception type: [WebSocketError]", I'm wondering if there is any adjustment on my side can fix the issue?

out of memory

Server Crashes with message:

INFO Jester is making jokes at http://0.0.0.0:8000
Starting 1 threads
DEBUG GET /ws
out of memory

Server

import jester
import ws, ws/jester_extra

settings:
  port = Port(8000)

routes:
  get "/ws":
    var ws = await newWebSocket(request)
    await ws.send("Welcome to simple echo server")
    while ws.readyState == Open:
      let packet = await ws.receiveStrPacket()
      await ws.send(packet)

Client

let ws = new WebSocket("ws://localhost:8000/ws")
ws.send("hi")

dont work

server never connects the client
tried all examples
all just "Socket closed"

Can't ping eninge io websocket

Based on https://github.com/socketio/engine.io-protocol/tree/v3 client need to ping server with message 2 to ping a server or connection will be closed.
But when I'm trying to send message with value 2 using ws there is no response (again when using any chrome websockets plugins or js there is pong of value 3) So its probably msg formatting problem (?)
I was trying

wes.send("2")
wes.send("2", opcode=Opcode.Binary)
wes.send("2", opcode=Opcode.Ping)

Problem running on windows

Typo in README (complaint -> compliant)?

The README reads, under "Features:"

I assume this is a typo, and "compliant" is meant. Usually, a typo is easy to correct, but there, it changes the implied meaning drastically: either ws disagrees with the websocket protocol implementation ("complaint"), or it agrees with the protocol ("compliant").


Aside, I also think it should read:

which is more of a normal sentence, and makes it immediately clear what the link is about.

Poor performance while sending data through opened sockets

Hello I was trying to implement some sort of pub/sub service using this library and jester. I managed to write this piece of code:

import asyncdispatch, jester
import ws, ws/jester_extra
import std/strformat                                          
import std/sets
include types/ws_hash #This is just a file I wrote that makes the WebSocket type hashable and makes it able to use it with a HashSet

var socketPool = initHashSet[WebSocket]()

router cnsRouter:
  get "/count":
    resp fmt"{socketPool.len} connection(s)"

  get "/pub":
    var count = 0
    for socket in socketPool:
        await socket.send("Test message")
        count += 1

    resp fmt"Sent {count} msg(s)"

  get "/sub":
    var ws = await newWebSocket(request)
    socketPool.incl(ws)

    try:
      while ws.readyState == Open:
        discard await ws.receiveStrPacket()
    except:
      echo "Connection closed"
    finally:    
      socketPool.excl(ws)

    resp ""

It works fine however it takes too much time to broadcast the message to all opened sockets. In my computer takes almost 1s per connection to deliver the message and it seems it goes increasing by 1s the request time on the /pub endpoint if you keep opening connections to the /sub endpoint.
Is there any particular reason why this happens? I'm aware this is a community project and it can have its drawbacks but I think 1s per connection is an excessive amount of time.
Maybe I'm doing something wrong? I'll gladly appreciate all the comments. Thanks

Test example fails

I'm trying to write a short test example. But it fails.

`
import ws, asyncdispatch

let baseurl = "wss://stream.binance.com:9443/ws/"
let stream = "btcusdt@bookTicker"
let payload = baseurl & stream

var wsoc = await newWebSocket(payload)
echo await wsoc.receiveStrPacket()
wsoc.close()
`

The error message I receive is :

App.nim(7, 18) template/generic instantiation of await from here
C:\Dev\nim-1.6.4_x64\nim-1.6.4\lib\pure\asyncmacro.nim(130, 3) Error: 'yield' only allowed in an iterator

undeclared identifier: 'SslError'

This package is a part of important_packages which are continuously tested with every new commit to Nim's repository.

Since recently, it started to fail, with this error: ws.nim(422, 10) Error: undeclared identifier: 'SslError'.

I think this is something on your side (and not something that broke in the latest devel), and it might be connect to the Better Exception Handling commit.

"yield only allowed in iterator" error when trying example

Hello,

I'm trying to run the example client script in the readme. This is my complete script:

import ws, asyncdispatch, asynchttpserver

var ws = await newWebSocket("ws://127.0.0.1:9001/ws")
echo await ws.receiveStrPacket()
await ws.send("Hi, how are you?")
echo await ws.receiveStrPacket()
ws.close()

However, when running it, I get this error:

% nim c -r "/nim/helloworld.nim"
Hint: used config file '/usr/local/Cellar/nim/1.4.4/nim/config/nim.cfg' [Conf]
Hint: used config file '/usr/local/Cellar/nim/1.4.4/nim/config/config.nims' [Conf]
.................................................
/nim/helloworld.nim(3, 16) template/generic instantiation of `await` from here
/usr/local/Cellar/nim/1.4.4/nim/lib/pure/asyncmacro.nim(144, 3) Error: 'yield' only allowed in an iterator

What did I do wrong? The server example actually works.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.