i

Python Programming

Python Socket Programming

Socket Programming

The sockets enable programs to send and receive data bi-directionally at any given moment. In this we learn how you can send data from device-to-device, client-to-server, and vice versa using socket programming.

Creating Sockets

Python provides a socket class so developers easily implement socket objects in source code. Should use socket object in program start importing socket library. No need to install with a package manager, it comes out of box with python.

Import socket

Now we can create socket objects insidecode

sock= socket.socket(socket.AF_INET, socket.SOCK_STREAM)

Abovewill creates socket object that we are storing in “sock” variable. The constructor is provided family and type parameter respectively.  The family parameter is set the default value, which is Address Format Internet.

The type parameter set to Socket Stream, also default which enables “sequenced, reliable, two-way connection-based byte streams” over TCP1.

Once we initialized socket object, we can use methods to open a connection, send data, receive data and finally close the connection.

sock.connet((‘0.0.0.0’, 8080))

sock.sent(“twenty-five bytes send”)

sock.recv(4096)

sock.close()