Computer >> Computer tutorials >  >> Programming >> Python

Socket programming In Python


In bidirectional communications channel, sockets are two end points. Sockets can communicate between process on the same machine or on different continents.

Sockets are implemented by the different types of channel-TCP, UDP.

For creating Socket, we need socket module and socket.socket () function.

Syntax

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

Different methods in Server Socket

my_socket.bind()

This method is used for binding address (hostname, port number pair) to socket.

my_socket.listen()

This method is used for set up and start TCP listener.

my_socket.accept()

This method is used for accepting TCP client connection, waiting until connection arrives (blocking).

Different methods in Client Socket

my_socket.connect()

This method actively initiates TCP server connection.

General Socket Methods

my_socket.recv()

This method receives TCP message

my_socket.send()

This method transmits TCP message

my_socket.recvfrom()

This method receives UDP message

my_socket.sendto()

This method transmits UDP message

my_socket.close()

This method closes 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