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 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
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