Foundations of Python

You are currently auditing this course.
127 / 134

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


Please login to comment

12 Comments

import socket 
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('www.py4inf.com' , 80))

mysock.send(b'GET /code/romeo.txt HTTP/l.0\r\nHost: www.py4inf.com\r\n\r\n')

while True:
    data = mysock.recv(512)    
    if (len(data) < 1):
        break
    print(data)
mysock.close()

 

b'HTTP/1.1 400 Bad Request\r\nServer: nginx\r\nDate: Sun, 16 Feb 2025 07:58:35 GMT\r\nContent-Type: text/html\r\nContent-Length: 150\r\nConnection: close\r\n\r\n<html>\r\n<head><title>400 Bad Request</title></head>\r\n<body>\r\n<center><h1>400 Bad Request</h1></center>\r\n<hr><center>nginx</center>\r\n</body>\r\n</html>\r\n'

  

I am not able to get the required output.Can anyone please help me?

 

  Upvote    Share

Hi Jasmeen,

You're getting a 400 Bad Request error because there's a small mistake in your HTTP request format.

You wrote HTTP/l.0 (which has an incorrect lowercase "l" instead of digit "1").

The correct format is HTTP/1.0 or HTTP/1.1.

Also, the request must end with double \r\n\r\n to indicate the end of headers.

Fixed Code:

import socket 

mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('www.py4inf.com', 80))

# Corrected GET request
cmd = b'GET /code/romeo.txt HTTP/1.0\r\nHost: www.py4inf.com\r\n\r\n'
mysock.send(cmd)

while True:
    data = mysock.recv(512)    
    if len(data) < 1:
        break
    print(data.decode())  # Decoding bytes to readable text

mysock.close()
  Upvote    Share

Thank you . Got it

  Upvote    Share

Also when I run the server.py and client.py process they are running foreever even though I am running them simultaneously.

#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

Socket successfully created
socket binded to 4042
socket started listening
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-2-89c37ab838a1> in <module>
     21 while counter < 5:
     22     # Keep establishing connection with clients
---> 23     c, addr = s.accept()
     24     print ('Got a connection from', addr )
     25     counter+= 1

/usr/local/anaconda/lib/python3.6/socket.py in accept(self)
    203         For IP sockets, the address info is a pair (hostaddr, port).
    204         """
--> 205         fd, addr = self._accept()
    206         # If our type has the SOCK_NONBLOCK flag, we shouldn't pass it onto the
    207         # new socket. We do not currently allow passing SOCK_NONBLOCK to

KeyboardInterrupt: 

#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()

 

  Upvote    Share

Your server.py and client.py scripts are working as expected in terms of connection handling. However, the issue you're facing—where the server keeps running forever—is because s.accept() is a blocking call. That means the server is waiting indefinitely for a new connection before proceeding to the next iteration of the loop. If you are not running the client.py enough times (at least 5 times, as per your counter < 5 condition), the server will keep waiting for new connections.

 

  Upvote    Share

Can you please elaborate server & client programs?

I created server & client programs and running it but looks like server is not listening to client. Can you please help?

  Upvote    Share

Make sure to run the server program first, and then run the client program. If you're still facing issues, here are a few things to check:

Correct IP and Port: Double-check that the server and client are using the same IP address and port.

No typos or errors: Make sure there are no typos or errors in your code, especially in the server and client addresses.

If the issue persists, you may want to check for exceptions or errors that might be occurring during execution. Feel free to share any error messages you're encountering for further assistance.

  Upvote    Share

hi, I am still having my doubts with Socket programming. is there a book that you can suggest to get better understanding of socket programming?

 1  Upvote    Share

how long until I start the client process? the server is taking forever to run..

  Upvote    Share

Hi Suma,

You need to run both server.py and client.py at the same time as a server-client architecture requires both client and server to be active to interact. You can open a separate web console to run python client.py.

  Upvote    Share

How can I test the server.py and client.py. Would you please help on this?

  Upvote    Share

Hi

You can start the server and client process and check whether it's not showing any error.

Thanks

  Upvote    Share