Simple Server and Client Chat using Python

Server-Client Chat 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 protocol
  • bind() – 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 machine
  • gethostbyname() – translates a host name to IPv4 format address
  • recv() – receives message sent through TCP
  • decode() – decodes the message using the codec
  • send() – sends message sent through TCP
For more details on methods, functions, module, and objects, refer to the official site of Python (python.org).

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 protocol
  • connect() – connects to a server socket at address
For more details on methods, functions, module, and objects, refer to the official site of Python (python.org).

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.

Python Open With

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.

Python Server Chat

3. Run the client.py script in Python application using the local IP address sent by the server (accept the invitation).

Python Client Chat

4. Sent and/or receive messages from the server/client mutually.

Python Server Chat Messages

Comments

  1. Wrong source code is given above.... both code is same

    ReplyDelete
  2. Hi 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

    ReplyDelete
    Replies
    1. Both computers must be connected through the same network. If fine, check firewall and program permission.

      Delete
  3. Is 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.

    I want to send message in 2 line and should see the message on the recipient side in 2 lines without even the recipient responding.

    ReplyDelete
    Replies
    1. Not possible. Always server must grant access permission to clients. But we can reduce time for connection.

      Assign 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).

      Delete
    2. If your message is predefined, you can use "pickle" to send the message to a socket. Using pickle, you can serialize Python objects.

      Delete
  4. How can I use this on pcs connected to different network??? I googled it but can't find any acceptable solution.

    ReplyDelete
  5. If PCs are connected to different network, use public IPs (Public IP Address) of the PCs. If it fails, port-forward through modem router.

    ReplyDelete
  6. Amazing sir its working for server-client chat .... can you provide code for multiple client chat with the server..?

    ReplyDelete
    Replies
    1. Try to extract code from https://github.com/Rishija/python_chatServer

      Delete
  7. This comment has been removed by the author.

    ReplyDelete
  8. Hi, 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

    ReplyDelete
    Replies
    1. Check whether the packages/modules/functions of Python3 is available in the Python. If not, do alternative changes accordingly.

      Delete
  9. why is my .py files closing immediately after opening

    ReplyDelete
    Replies
    1. Execute the program as given in this tutorial. Don't double-click and run the .py file, it may close immediately after opening.

      Delete
  10. sir it is displying anerror while connecting client and server using ip .
    It is displaying error in below line--s.connect((host , port))
    plz help us sir ASAP

    ReplyDelete
    Replies
    1. Run the programs with Admin privileges. If not works, check the IP address and Firewall block list in OS.

      Delete
  11. How would we tweak this to allow for multiple chat clients?

    ReplyDelete
    Replies
    1. Try the following GitHub source code repositories. It will be very much helpful to you.

      https://github.com/Rishija/python_chatServer
      https://github.com/AakashMallik/Server-Client-multi-chat-sockets

      Delete
  12. Sir when you said use public ip address are we supposed to just type the public ip or make some changes into the program

    ReplyDelete
    Replies
    1. You 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.

      Delete
  13. hello 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.

    File "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?

    ReplyDelete
    Replies
    1. Both computers must be connected in the same network. If it is fine, check the firewall and Python program permission of both computers.

      Delete
    2. How do make the server running and able to receive data from client even if client closes connection then later re opens it ?

      Delete
    3. It is not possible in server-client connection. You can try automatic re-login methods with cookies, catches, or sessions.

      Delete

Post a Comment

Most Popular Posts

TNEB Bill Calculator

TNEB Bill Calculator (New)

Technical Questions