Python- Networking Example | Socket programming

1. Refer client.py and server .py

2. # Following would start a server in background.
$ python server.py &

# Once server is started run client as follows:
$ python client.py

Got connection from ('127.0.0.1', 48437)
Thank you for connecting



# This is client.py file


#!/usr/bin/python       

import socket               # Import socket module

s = socket.socket()         # Create a socket object
#host = socket.gethostname() # Get local machine ip
host ='192.168.29.137' #
Get local machine ip
 port = 12345                # Reserve a port for your service.

s.connect((host, port))
print s.recv(1024)
s.close                     # Close the socket when done




# This is server.py file

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = gethostname() # Get local machine name
#host ='0.0.0.0'  #use in case two computers
port = 12345                # Reserve a port for your service.
s.bind((host, port))        # Bind to the port

s.listen(5)                 # Now wait for client connection.
while True:
   c, addr = s.accept()     # Establish connection with client.
   print 'Got connection from', addr
   c.send('Thankyou and noted')
   c.close()                # Close the connection

Reactions: