Writing a simple TCP Server & Client Application in Python

Posted: April 28, 2012 in Programming, Python
Tags: , , , , , , , , , ,

In the server side, we have to create a socket, Bind the socket to the address and port, and then set it to listening state and waits for the client to connect. When a client requests a connection, the server then accepts the connection.

Make sure you opened up two Python Shells (or Python IDLEs) so that you can run both the client and server.

This is a very basic program that sends a string of data from the server to the client and displays it to the client.

TCP SERVER

# TCP Server Code

host="127.0.0.1"			    # Set the server address to variable host
port=4446 				    # Sets the variable port to 4446
from socket import *	 		    # Imports socket module

s=socket(AF_INET, SOCK_STREAM)

s.bind((host,port))     		    # Binds the socket. Note that the input to
                                            # the bind function is a tuple

s.listen(1) 		        	    # Sets socket to listening state with a  queue
                                            # of 1 connection

print "Listening for connections.. "

q,addr=s.accept()			    # Accepts incoming request from client and returns
                                            # socket and address to variables q and addr

data=raw_input("Enter data to be send:  ")  # Data to be send is stored in variable data from
                                            # user

q.send(data) 		        	    # Sends data to client

s.close()

# End of code

 ___________________________________________________________________________________

TCP Client

In the TCP Client, we need to create the socket first, then connect to the server by using the socketname.connect((ipaddress,port)) . Then you need to receive the data which is send from the server, this is done by using the function socketname.recv(size)

# TCP Client Code

host="127.0.0.1" 			# Set the server address to variable host

port=4446 				# Sets the variable port to 4446

from socket import *			 # Imports socket module

s=socket(AF_INET, SOCK_STREAM)		# Creates a socket

s.connect((host,port))			# Connect to server address

msg=s.recv(1024)			# Receives data upto 1024 bytes and stores in variables msg

print "Message from server : " + msg

s.close()                            # Closes the socket
# End of code

Happy Coding!

CheerS!!

ΞXΤRΞМΞ-X

Comments
  1. Nancy says:

    Hi!
    I am a beginner and know nothing about this, though I would really like to learn.
    Do you mind explaining how to run the code in my windows computer and what I’ll have to change to make it work as well?

    Thank you so much!

  2. Rufus says:

    minor typo: port number is 4446, comments say 4444

  3. kabmorry says:

    I get this error: Traceback (most recent call last):
    File “C:/Python33/Server_Side_Chat.py”, line 9, in
    s.bind((host,port))
    TypeError: an integer is required

    PLEASE ADVISE

    • ΞXΤЯ3МΞ says:

      @kabmorry, Please check the second line of the code, if you have entered the port as:

      port=4446 instead of port=’4446′ . The right way is port=4446.

      Hope this helps

      Regards
      ΞXΤЯ3МΞ

      • kabmorry says:

        Thank you! Worked Fine for the Server but gave this error for the client side:

        Traceback (most recent call last):
        File “C:/Python33/Client_Side_Chat.py”, line 9, in
        s.connect((host,port))
        ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it

  4. kabmorry says:

    Got it!

    NOW, help converting bytes to str during the sending of data q.send(data)

    How do I convert that?

  5. Mrinal Wahal says:

    When I connect my client to the server over wifi, it displays an error : “[Errno 10060] A connection attempt failed because the connected party did not respond after a period of time or host has failed to respond.” But it workds damn fine when I connect the client to the server on the same system through different terminals. Please Help !

    • ΞXΤЯ3МΞ says:

      @Mrinal Wahal, The example source code posted as I have mentioned works if you run the server and client is on the same pc (as the host is mentioned as 127.0.0.1).

      If you are trying it from two seperate pcs, make sure that you need to change the hosts ips in the server and the client source code accordingly, make sure the ports used are open in both the server and client pc.

      Check connectivity between both pcs: Try to ping and make sure you have connectivity between both the client pc and the server pc.

      In the example code that I have posted above, both the server and client are using port number : 4446. If this port is not open in either of the server pc / client pc, the connection attempt would fail.

      So, if the port is closed, you can either forward that port or simply change the port number in the code to a port that is already open in both pcs.

      Hope this helps!

      Regards
      ΞXΤRΞМΞ

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s