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
Taking you to the next exercise in seconds...
Want to create exercises like this yourself? Click here.
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()
I am not able to get the required output.Can anyone please help me?
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
orHTTP/1.1
.Also, the request must end with double
\r\n\r\n
to indicate the end of headers.Fixed Code:
Upvote ShareThank you . Got it
Upvote ShareAlso 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
#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()
Your
server.py
andclient.py
scripts are working as expected in terms of connection handling. However, the issue you're facing—where the server keeps running forever—is becauses.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 theclient.py
enough times (at least 5 times, as per yourcounter < 5
condition), the server will keep waiting for new connections.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 ShareMake 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 Sharehi, 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 Sharehow long until I start the client process? the server is taking forever to run..
Upvote ShareHi 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 ShareHow can I test the server.py and client.py. Would you please help on this?
Upvote ShareHi
You can start the server and client process and check whether it's not showing any error.
Thanks
Upvote Share