Home » 2017 » August » 19 » Socket programming in Python : Client - Server architecture

10:44 AM
Socket programming in Python : Client - Server architecture

Hi Guys,

Today in this article we shall build up a small program to understand client -server communication using socket in Python.


 

Server side:

1. Create a socket:

socket(socket family, type(TCP/UDP), protocol)

-- Family or domain could be AF_INET or AF_UNIX

-- Type could be TCP: SOCK_STREAM or UDP : SOCK_DGRAM

-- Protocol is left bank, by default it is 0.

 

2. Bind socket

socket.bind(IPaddress, portNo)

-- bind the socket to a system's ip address and port number

-- the port number can be anything of 0-65365

 

3. Start listening

socket.listen(no of maximum connections)

-- listen sets the maximum no of connections from clients

 

4. Accept connections

socket.accept()

-- The above method accepts connections and returns the socket object of the client who establishes a connection.

5.  Send /receive data

clientSock.send(msg)

-- The above method send msg to clients connected through clientSock object

reply=clientSock.receive(size)

it will receive msg of size not more than size byte.


 

Client side

 

1. Create a socket as above

2. Connect to server

sockObj.connect(hostname,port)

3. send/receive data

Note: Please understand that same skeleton is followed in C, Java, VB.net and Python,


 

Some of the methods of socket objects in python:

     |  accept() -- accept a connection, returning new socket and client address
     |  bind(addr) -- bind the socket to a local address
     |  close() -- close the socket
     |  connect(addr) -- connect the socket to a remote address
     |  connect_ex(addr) -- connect, return an error code instead of an exception
     |  dup() -- return a new socket object identical to the current one [*]
     |  fileno() -- return underlying file descriptor
     |  getpeername() -- return remote address [*]
     |  getsockname() -- return local address
     |  getsockopt(level, optname[, buflen]) -- get socket options
     |  gettimeout() -- return timeout or None
     |  listen(n) -- start listening for incoming connections
     |  makefile([mode, [bufsize]]) -- return a file object for the socket [*]
     |  recv(buflen[, flags]) -- receive data
     |  recv_into(buffer[, nbytes[, flags]]) -- receive data (into a buffer)
     |  recvfrom(buflen[, flags]) -- receive data and sender's address
     |  recvfrom_into(buffer[, nbytes, [, flags])
     |    -- receive data and sender's address (into a buffer)
     |  sendall(data[, flags]) -- send all data
     |  send(data[, flags]) -- send data, may not send all of it
     |  sendto(data[, flags], addr) -- send data to a given address
     |  setblocking(0 | 1) -- set or clear the blocking I/O flag
     |  setsockopt(level, optname, value) -- set socket options
     |  settimeout(None | float) -- set or clear the timeout
     |  shutdown(how) -- shut down traffic in one or both directions

 


 

Functions of sockets are as below:

   
    socket() -- create a new socket object
    socketpair() -- create a pair of new socket objects [*]
    fromfd() -- create a socket object from an open file descriptor [*]
    gethostname() -- return the current hostname
    gethostbyname() -- map a hostname to its IP number
    gethostbyaddr() -- map an IP number or hostname to DNS info
    getservbyname() -- map a service name and a protocol name to a port number
    getprotobyname() -- map a protocol name (e.g. 'tcp') to a number
    ntohs(), ntohl() -- convert 16, 32 bit int from network to host byte order
    htons(), htonl() -- convert 16, 32 bit int from host to network byte order
    inet_aton() -- convert IP addr string (123.45.67.89) to 32-bit packed format
    inet_ntoa() -- convert 32-bit packed format IP to string (123.45.67.89)
    ssl() -- secure socket layer support (only available if configured)
    socket.getdefaulttimeout() -- get the default timeout value
    socket.setdefaulttimeout() -- set the default timeout value
    create_connection() -- connects to an address, with an optional timeout and
                           optional source address.

 


 

A very basic sample program to practice:

Server program:

#!/usr/bin/python
import socket

#create socket object with a domain and type and protocol, protocol is 0 by default
sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM);
print "socket created"

hostna=socket.gethostname();  #gives the ipname of the system
portt=8888;  #range 0 to 65535

#bind the socket to a host and a port number
sock.bind((hostna,portt));

sock.listen(5);  # listens to maximum 5 connections from clients
print "Listening on " + hostna + " and port no. : ", portt;

while 1 :

    clientsocket,addr= sock.accept();
    #returns a socket object for client who is trying to connect to server.

    print "Accepted connection from", str(addr);
    messag="Thanks for connecting";

    #while sending a message to client, we have to use client socket from which we got connection
    clientsocket.send(messag.encode('ascii'));

    replyFromClient=clientsocket.recv(1024)
    print "Reply from client : " + replyFromClient.decode('ascii');
     clientsocket.close();    
sock.close();

 

Client side program:

#!/usr/bin/python

import socket

sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM);
#creates a socket object

hostna=socket.gethostname();
try:
    sock.connect((hostna,8888));

#here instead of localhost name, you can specify the ip address of the server.
    msg=sock.recv(1024);
#receives data from server upto 1024 byes
    print msg.decode('ascii');
    replytoServer="thanks server"
    sock.send(replytoServer.encode('ascii'));

except socket.error as msg:
    print "Error while connecting to server " + str(msg[0]);

 

Run the server program first , you will get below message:

shanky@shanky-Aspire-ES1-572 ~/Python $ ./socketServer.py
socket created
Listening on shanky-Aspire-ES1-572 and port no. :  8888

 

Then run the client,

 

shanky@shanky-Aspire-ES1-572 ~/Python $ ./socketClient.py
Thanks for connecting

 

This is very basic snippet. I hope this is self understandable. If you have any queries please comment, report back

 

 
 

Category: Programming Languages | Views: 1217 | Added by: shanky | Tags: socekt ptrogramming, client-server, python, Socket | Rating: 0.0/0

Related blogs


You may also like to see:



Total comments: 0
ComForm">
avatar