Learning Python Network Programming

(Sean Pound) #1
Chapter 7

A non-blocking socket I/O


In this section, we will see a small example code snippet to test a non-blocking socket
I/O. This is useful if you know that the synchronous blocking connection is not
necessary for your program. The following is an example of non-blocking I/O:


import socket

if __name__ == '__main__':
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setblocking(0)
sock.settimeout(0.5)
sock.bind(("127.0.0.1", 0))

socket_address =sock.getsockname()
print("Asynchronous socket server launched on socket: %s"
%str(socket_address))
while(1):
sock.listen(1)

This script will run a socket server and listen in a non-blocking style. This means you
can connect more clients who won't be necessarily blocked for I/O.


Securing sockets with TLS/SSL


You have probably come across the discussion around secure web communication
using Secure Socket Layer (SSL), or more precisely Transport Layer Security (TLS),
which is adopted by many other high-level protocols. Let us see how we can wrap a
plain sockets connection with SSL. Python has the built-in ssl module, which serves
this purpose.


In this example, we would like to create a plain TCP socket and connect to an HTTPS
enabled web server. Then, we can wrap that connection using SSL and check the
various properties of the connection. For example, to check the identity of the remote
web server, we can see if the hostname is same in the SSL certificate as we expect it to
be. The following is an example of a secure socket-based client:


import socket
import ssl
from ssl import wrap_socket, CERT_NONE, PROTOCOL_TLSv1, SSLError
from ssl import SSLContext
Free download pdf