Skip to content

Instantly share code, notes, and snippets.

@dom96
Created January 25, 2016 00:07
Show Gist options
  • Save dom96/3b1c21dcc2598aae5961 to your computer and use it in GitHub Desktop.
Save dom96/3b1c21dcc2598aae5961 to your computer and use it in GitHub Desktop.
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment