Simple Server and Client Chat using Python
In Python language, socket (or network socket) is a module used to communicate between two computers. It provides two types of interface to access the network, namely low-level (platform dependent connections — Example: Telnet) and high-level (application dependent connections — Example: HTTP, FTP, SMTP, etc.). This is a simple tutorial to establish the low-level socket connection between server and client to communicate messages using the TCP/IP protocol.
Server and Client Chat
In this tutorial, I have used two scripts server.py to serve data by sending an invitation to the client, and client.py to receive data on acceptance of the invitation. After accepting the invitation, both server and client share messages mutually.
— Server —
An server script performs the sequence of functions such as socket()
, bind()
, listen()
, and accept()
(repeats for more than one client) to communicate with the client. The description of each functions used in the server script are given bellow:
socket()
– creates a socket using the address family, socket type and protocolbind()
– binds the socket to the given address (host name, and port number pair)listen()
– enables a server to accept connections from the client(s)accept()
– waits and accepts connection request from the client(s)gethostname()
– retrieves host name of the machinegethostbyname()
– translates a host name to IPv4 format addressrecv()
– receives message sent through TCPdecode()
– decodes the message using the codecsend()
– sends message sent through TCP
Source Code
# server.py
import time, socket, sys
print("\nWelcome to Chat Room\n")
print("Initialising....\n")
time.sleep(1)
s = socket.socket()
host = socket.gethostname()
ip = socket.gethostbyname(host)
port = 1234
s.bind((host, port))
print(host, "(", ip, ")\n")
name = input(str("Enter your name: "))
s.listen(1)
print("\nWaiting for incoming connections...\n")
conn, addr = s.accept()
print("Received connection from ", addr[0], "(", addr[1], ")\n")
s_name = conn.recv(1024)
s_name = s_name.decode()
print(s_name, "has connected to the chat room\nEnter [e] to exit chat room\n")
conn.send(name.encode())
while True:
message = input(str("Me : "))
if message == "[e]":
message = "Left chat room!"
conn.send(message.encode())
print("\n")
break
conn.send(message.encode())
message = conn.recv(1024)
message = message.decode()
print(s_name, ":", message)
— Client —
An client script performs the sequence of functions such as socket()
, and connect()
to communicate with the server. The description of each functions used in the server script are given bellow:
socket()
– creates a socket using the address family, socket type and protocolconnect()
– connects to a server socket at address
Source Code
# client.py
import time, socket, sys
print("\nWelcome to Chat Room\n")
print("Initialising....\n")
time.sleep(1)
s = socket.socket()
shost = socket.gethostname()
ip = socket.gethostbyname(shost)
print(shost, "(", ip, ")\n")
host = input(str("Enter server address: "))
name = input(str("\nEnter your name: "))
port = 1234
print("\nTrying to connect to ", host, "(", port, ")\n")
time.sleep(1)
s.connect((host, port))
print("Connected...\n")
s.send(name.encode())
s_name = s.recv(1024)
s_name = s_name.decode()
print(s_name, "has joined the chat room\nEnter [e] to exit chat room\n")
while True:
message = s.recv(1024)
message = message.decode()
print(s_name, ":", message)
message = input(str("Me : "))
if message == "[e]":
message = "Left chat room!"
s.send(message.encode())
print("\n")
break
s.send(message.encode())
Implementation Steps
1. Run the server.py script in Python application.
2. Note down the local IP address and pass it to the clients (invitation). Alternatively, you can also get the local IP address through online using L-IP tool.
3. Run the client.py script in Python application using the local IP address sent by the server (accept the invitation).
4. Sent and/or receive messages from the server/client mutually.
Wrong source code is given above.... both code is same
ReplyDeleteThanks for your comment. I'll rectify the anomalies.
DeleteClient source code updated. Thanks for commenting.
DeleteHi Ashok. I tried to run these two scripts and it worked well on my computer. I tried to connect the server, which is my own computer, from another computer it raised the timeout error. what might be the reason for that? thanks
ReplyDeleteBoth computers must be connected through the same network. If fine, check firewall and program permission.
DeleteThis comment has been removed by the author.
ReplyDeleteIs there any way, that the server and the client both are ready to to listen to new message or ready to send a new message at any time, here the only problem I personally felt is both sides have to reply simultaneously.
ReplyDeleteI want to send message in 2 line and should see the message on the recipient side in 2 lines without even the recipient responding.
Not possible. Always server must grant access permission to clients. But we can reduce time for connection.
DeleteAssign static ip for both server and client machines. Also, enter the ip and port number of the server and client machines in the coding itself (server.py and client.py).
If your message is predefined, you can use "pickle" to send the message to a socket. Using pickle, you can serialize Python objects.
DeleteHow can I use this on pcs connected to different network??? I googled it but can't find any acceptable solution.
ReplyDeleteIf PCs are connected to different network, use public IPs (Public IP Address) of the PCs. If it fails, port-forward through modem router.
ReplyDeleteThanks for your clean codes
ReplyDeleteAmazing sir its working for server-client chat .... can you provide code for multiple client chat with the server..?
ReplyDeleteTry to extract code from https://github.com/Rishija/python_chatServer
DeleteThis comment has been removed by the author.
ReplyDeleteSorry. I have no PPT for this tutorial.
DeleteHi, I want to run same code using python not with python3 how is that possible should i make any changes when i compile with python its not coming
ReplyDeleteCheck whether the packages/modules/functions of Python3 is available in the Python. If not, do alternative changes accordingly.
Deletewhy is my .py files closing immediately after opening
ReplyDeleteExecute the program as given in this tutorial. Don't double-click and run the .py file, it may close immediately after opening.
Deletesir it is displying anerror while connecting client and server using ip .
ReplyDeleteIt is displaying error in below line--s.connect((host , port))
plz help us sir ASAP
Run the programs with Admin privileges. If not works, check the IP address and Firewall block list in OS.
DeleteHow would we tweak this to allow for multiple chat clients?
ReplyDeleteTry the following GitHub source code repositories. It will be very much helpful to you.
Deletehttps://github.com/Rishija/python_chatServer
https://github.com/AakashMallik/Server-Client-multi-chat-sockets
Sir when you said use public ip address are we supposed to just type the public ip or make some changes into the program
ReplyDeleteYou can use local IP for connecting within a LAN. Moreover, you can also use public IP if you are connected through a webserver. The only thing you have to understand is your IP must be discoverable within a network.
Deletehello sir, I get an error when running the file "client", more precisely when I enter the ip address of the "server". after I waited for a while, and I get an error like this.
ReplyDeleteFile "c:\Users\User\Desktop\client.py", line 17, in
s.connect((host, port))
TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not respond properly after a
period of time, or established connection failed because connected host has failed to respond
can you help me solve the error I'm experiencing?
Both computers must be connected in the same network. If it is fine, check the firewall and Python program permission of both computers.
DeleteHow do make the server running and able to receive data from client even if client closes connection then later re opens it ?
DeleteIt is not possible in server-client connection. You can try automatic re-login methods with cookies, catches, or sessions.
Delete