14 – Socket programming in Python

Have you ever wondered how to two computers communicate using Ethernet or WI-FI? They use the server-client model of communication. Server-Client communication can be achieved by using socket programming. Sockets are channels established for two-way communication that is bound to a port and an IP.  Socket programming in python is discussed here.

SERVER CODE:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#MYBTECHPROJECTS
 
#Import the socket module
import socket
 
#create a object for the socket class
s = socket.socket()
 
#Get the localhost IP
host = socket.gethostname()
 
#Assign a port for the socket to be bonded
port = 12345
 
#Bind the socket to the IP and port
s.bind((host, port))        
 
s.listen(5)
 
#Continuosly accept connections 
while True:
   c, addr = s.accept()    
   print 'Got connection from', addr
 
   #Receive data
   print c.recv(1024)
 
   #Send data
   c.send('Response from Server')
 
   c.close()

NOTE: 

This code is to run both server and client on the same machine. To run on different computers find the IP address of the network interface that is to be used and change the host. If I am using WI-FI find the IP address assigned to your Laptop using ipconfig in Command prompt.

host=172.22.19.228

CLIENT CODE:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#MYBTECHPROJECTS
 
#Import the socket module
import socket
 
#create a object for the socket class
s = socket.socket()
 
#create a object for the socket class
host = socket.gethostname()
 
#Assigna port for socket to be binded
port = 12345                
 
#Connect to the specified ip and port
s.connect((host, port))
 
#send data
s.send('Request from client')
 
#receive data
print s.recv(1024)
 
s.close

OUTPUT:

 

 

SHARE THIS!!!

Gowtham S

Gowtham is a programming enthusiast. His field of interest includes Arduino, NodeMCU, Raspberry Pi, and Python. To know more about him visit https://mybtechprojects.tech/about-us/.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.