Create Simple TCP Server And Client Using Python Socket Module - Part 1

Namaste Friends,


                                 
                                          This Is Our first tutorial about python Socket Programming but not last part!! .  So, In This Tutorial, I Am Going To Show You Some Real Practical Examples With Details Of  How To Create A Simple Tcp Server And A Simple Client.

Here,
         I Collected Many Content From Python Official Site and from All Over The Internet because nothing is enough in tutorials.


Keep Reading Without Skipping Any Content And Line.

So, Let's Start Our Tutorial,

Our First Question Is

Q 1. What Is socket?


Ans. In Simple Word, socket is a low-level programming module specially used for networking purposes like create tcp/ip servers or clients and many more. in this module, you will find almost all features useful for creating server and client. if you want more detail, check python official page here

Q 2. What is Socket Module?

Ans. If You Know How To Use Socket Module Then, You Can Easily Create A Server Or A Clients. This Module Provides us capabilities to create new sockets, servers and other networking tools. This Module is like a base of other python network modules. if you want to use networking features in python then this module is your golden tool.


now, let's move ahead and talk about address families supported by python socket module.

normally, python socket module generally use  to create protocols are


  1.   socket.AF_INET
  2.   socket.AF_INET6




These Constant represent address family and protocol used for socket module first argument socket.socket().

here,

         these generally use constant representing socket type use for second argument of socket.socket().




  1. socket.SOCK_STREAM
  2. socket.SOCK_DGRAM


Now, Let's Move Ahead and
Check Some Useful Instance Methods



Table 1.

Instance methodDescription
sock.bind( (adrs, port) )Bind the socket to the address and port
sock.accept()Return a client socket (with peer address information)
sock.listen(backlog)Place the socket into the listening state, able to pend backlog outstanding connection requests
sock.connect( (adrs, port) )Connect the socket to the defined host and port
sock.recv( buflen[, flags] )Receive data from the socket, up to buflen bytes
sock.recvfrom( buflen[, flags] )Receive data from the socket, up to buflen bytes, returning also the remote host and port from which the data came
sock.send( data[, flags] )Send the data through the socket
sock.sendto( data[, flags], addr )Send the data through the socket
sock.close()Close the socket
sock.getsockopt( lvl, optname )Get the value for the specified socket option
sock.setsockopt( lvl, optname, val )Set the value for the specified socket option
The instance methods require a socket instance to be performed (returned from socket), 

Practical Example Of Tcp/IP Server And Client

 Here, I am Sharing My Demo Codes But If You Want More Better Example Then, You Can Modify these codes yourself. To Create This Example more easy to understand, i divided  server script in 4 steps:In First Step :
We will import module And creating socket object

Here, This Is First Step Code :


# step 1 : 

# Import Module
import socket

# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)



In Second Step :

Select IP Address For Binding. because After Providing IP Address We Can Control Our Server Script To accept connection from provided IP address. but if you want to accept of all IP Address connection.
then, use;

       '0.0.0.0'   or Just ' '

Second Setup Code :


# step 2 :

# IP and port for accepting connections
server_address = ('localhost', 10000)

# print server address and port
print "[+] Server IP {} | Port {}".format(server_address[0],server_address[1])

# bind socket with server
sock.bind(server_address)


In Third Step :

Here, In this Step, we will create function for accepting connection of client.


Third Step code:


# step 3 :

# Listen for incoming connections
sock.listen(1)

# Create Loop
while True:
    # Wait for a connection
    print '[+] Waiting for a client connection'
    # connection established
    connection, client_address = sock.accept()


And At The End,

Fourth Step :

Create Functions For receiving data from client,
send all received data back to client. And Also Combine All Our Previous Step Codes To Complete This Example.

code :

# step 4 :

import socket

# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# IP and port for accepting connections
server_address = ('localhost', 10000)

# print server address and port
print "[+] Server IP {} | Port {}".format(server_address[0],server_address[1])
# bind socket with server sock.bind(server_address) # Listen for incoming connections sock.listen(1) # Create Loop while True: # Wait for a connection print '[+] Waiting for a client connection'
    # connection established
    connection, client_address = sock.accept()
    try:
        print '[+] Connection from', client_address

        # Receive the data in small chunks and retransmit it
        while True:
            data = connection.recv(16)
            print 'received "%s"' % data
            if data:
                print 'sending data back to the client'
                connection.sendall(data)
            else:
                print 'no more data from', client_address
                break
            
    finally:
        # Close the connection
        connection.close()


Hahaha! Now, Our Server Script Is Ready To Use!
Then, Let's create a client script.

In First Step :

import module and create socket object

First Step Code :

#step 1 :

import socket


# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Connect the socket to the port where the server is listening
server_address = ('localhost', 10000)
print '[+] Connecting to %s Port %s' % server_address
sock.connect(server_address)

In Second Step :

Now, Combine All Functions In One Script.

Complete code :

#step 2:

import socket


# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Connect the socket to the port where the server is listening
server_address = ('localhost', 10000)
print '[+] Connecting to %s Port %s' % server_address
sock.connect(server_address)

try:
    
    # Send data
    message = 'This is the message.  It will be repeated.'
    print '[+] Sending "%s"' % message
    sock.sendall(message)

    # Look for the response
    amount_received = 0
    amount_expected = len(message)
    
    while amount_received < amount_expected:
        data = sock.recv(16)
        amount_received += len(data)
        print '[+] Received "%s"' % data

finally:
    print '[-] closing socket'
    sock.close()

Now, Let's Run This Script One by One And Check There Outputs

Server Script Output

[+] Server IP localhost | Port 10000
[+]  Waiting for a client connection
[+] Connection from ('127.0.0.1', 53782)
received "This is the mess"
sending data back to the client
received "age.  It will be"
sending data back to the client
received " repeated."
sending data back to the client
received ""
no more data from ('127.0.0.1', 53782)
[+]  Waiting for a client connection


Client Script Output

[+] Connecting to localhost Port 10000
[+] Sending "This is the message.  It will be repeated."
[+] Received "This is the mess"
[+] Received "age.  It will be"
[+] Received " repeated."
[-] closing socket



Yes! Yes! This Tutorials Ends Here. I Think, This is enough for today. So, Friends In my Next Tutorial You Will See more Useful Examples and codes.

For More Details about socket :

Reference Links : Python Official Site
And                      :  pymotw


If You Like My Article,
Like, Comment, Share.
Written By :
                  S.S.B


More Update, Visit Our Regularly. 
And Subscribe Our Blog, 


Follow Us and share it.
For Any Type of Suggestion Or Help
Contact me:
S.S.B
surajsinghbisht054@gmail.com 

Share this

Related Posts

Previous
Next Post »