Introducing non-blocking I/O

First, we are going to review a simple example of non-blocking I/O for the socket server. This script will run a socket server and listen in a non-blocking style. This means that you can connect more clients who won't be necessarily blocked for I/O.

You can find the following code in the server_socket_async.py file:

#!/usr/bin/env python3

import socket

if __name__ == '__main__':
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#unset blocking
sock.setblocking(0)
sock.settimeout(0.5)
sock.bind(("127.0.0.1", 12345))
socket_address =sock.getsockname()
print("Asynchronous socket server launched on socket: %s" %str(socket_address))
while(1):
sock.listen(1)

From a client point of view, when we make a socket non-blocking by calling setblocking(0), it will never wait for the operation to complete. So, when we call the send() method, it will put as much data in the buffer as possible and return.

You can find the following code in the client_socket_async.py file:

#!/usr/bin/env python3

import socket

if __name__ == '__main__':
sock = socket.socket()
sock.connect(("127.0.0.1", 12345))
#setting to non-blocking mode
sock.setblocking(0)
data = "Hello Python"
sock.send(data.encode())
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset