English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Socket programming in Python

In a bidirectional communication channel, sockets are two endpoints. Sockets can communicate between processes on the same machine or different continents.

Sockets are implemented by different types of channels TCP, UDP.

To create a Socket, we need the socket module and the socket.socket() function.

Syntax

my_socket = socket.socket(socket_family, socket_type, protocol=0)

Different methods in the server socket

my_socket.bind()

This method is used to bind the address (hostname, port pair) to the socket.

my_socket.listen()

This method is used to set up and start the TCP listener.

my_socket.accept()

This method is used to accept TCP client connections, waiting for connections to arrive (blocking).

Different methods in the client socket

my_socket.connect()

This method actively starts a TCP server connection.

General socket methods

my_socket.recv()

This method receives TCP messages

my_socket.send()

This method transmits TCP messages

my_socket.recvfrom()

This method receives UDP messages

my_socket.sendto()

This method transmits UDP messages

my_socket.close()

This method closes the socket

my_socket.gethostname()

This method returns the hostname.

Server Socket

Example

import socket
my_socket = socket.socket() # Create a socket object
my_host = socket.gethostname()
my_port = 00000# Store a port for your service.
my_socket.bind((my_host, my_port))
my_socket.listen(5) # Now wait for client connection.
while True:
   cl, myaddr = my_socket.accept() # Establish connection with client.
   print('Got connection from', myaddr)
   cl.send('Thank you for connecting')
   cl.close() # Close the connection

Client Socket

Example

import socket # Import socket module
my_socket = socket.socket() # Create a socket object
my_host = socket.gethostname() # Get local machine name
my_port = 00000# Store a port for your service.
my_socket.connect((my_host, my_port))
print(my_socket.recv(1024))
my_socket.close