Fix ResourceWarning: close sockets

Running tests on Python 3.5 compiled in debug mode (or just using -Wd command line option) emits some ResourceWarning because sockets are not closed. This commit fixes them.