Python Foundations

72 / 78

HTTP request using Socket




Not able to play video? Try with youtube

Python supports socket programming by providing 'socket' module. Socket programming enables connections and communications between two nodes. One node runs a process that listens for the requests on a particular port while another node sends the requests. It's a server-client relationship between two nodes.

In the below example, we connect to any public website like www.bing.com over port 80 using ipv4 address family (socket.AF_INET) over TCP protocol (sokcet.SOCK_STREAM). For UDP protocol, you can use socket.SOCK_DGRAM.

import socket
import sys

hostname = "www.bing.com"

try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print ("Socket successfully created here")
except socket.error as err:
    print ("Socket creation failed here with error %s" %(err))

# default port for socket
port = 80

try:
    host_ip = socket.gethostbyname(hostname)
except socket.gaierror:
    print ("Error resolving the host")
    sys.exit()

# connecting to the server
s.connect((host_ip, port))

print (f"Socket successfully connected to {hostname}")

Writing a simple server-client program

We will create 2 programs - one will act as server while another will act as client.

server.py

#server side program
import socket
# create a socket object
s = socket.socket()
print ("Socket successfully created")
# choose any random available port
port = 4042

# Next bind to the port
# empty string makes listen from all computers in the network
s.bind(('', port))
print ("socket binded to %s" %(port))
# start listening
s.listen(5)
print ("socket started listening")

# a forever loop until we interrupt it or
# an error occurs
counter = 0
while counter < 5:
    # Keep establishing connection with clients
    c, addr = s.accept()
    print ('Got a connection from', addr )
    counter+= 1
    # send a message to the client. encoding to send byte type.
    c.send('We listened to you'.encode())
    # Close the connection with the client
    c.close()
    # Breaking once connection closed
    #break

client.py

# client side program
import socket
# Create a socket object
s = socket.socket()
# port where server side program is listening
port = 4042
# connect to the server on local computer
s.connect(('127.0.0.1', port))
# receive data from the server and decoding to get the string.
print (s.recv(1024).decode())
# close the connection
s.close()

Start the server process. python server.py

Start the client process. python client.py


Loading comments...