Support using custom sockets within the runtime.

This is akin to supporting custom file descriptors, but for sockets. This
allows for the implementation of raw sockets in an external library, as well as
integration with other libraries that use sockets such as zeromq.
Code clean-ups for custom socket support.

This fixes a number of issues discussed in the pull request.