Skip to content

Instantly share code, notes, and snippets.

@dom96
Created January 25, 2016 00:07

Revisions

  1. dom96 renamed this gist Jan 25, 2016. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. dom96 created this gist Jan 25, 2016.
    34 changes: 34 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,34 @@
    import selectors, net

    type
    Data = ref object of RootRef
    someData: string

    var selector = newSelector()
    var sock = newSocket()
    # The {} means "Don't notify me about any events for this sock", the sock is still registered though
    selector.register(sock, {}, Data(someData: "Blah blah"))

    # The sock remains registered until it is closed.

    # Calling `selector.select()` will always return @[] because
    # none of the sockets that have been registered want to
    # receive any event notifications.

    # Let's update the events that 'sock' wants to hear about.
    # The following will ask selectors to give us notifications when `sock` becomes readable or writable.
    selector.update(sock, {EvRead, EvWrite})

    # Now, selector.select() will return @[] as long as `sock` is unreadable. Once it is
    # readable it will return @[(SelectorKey(fd: sock.fd, events: {EvRead, EvWrite}, Data(someData: "Blah blah")),
    # {EvRead})]

    # Because sockets are almost always writeable, you will likely also receive the same thing as
    # above but with {EvWrite} in the ReadyInfo.events field (ReadyInfo is a tuple).

    # Because receiving these notifications is only necessary when we actually *want* to
    # send some data through the socket, we can ...
    selector.update(sock, {EvRead})
    # ... to get rid of this notification.