Friday, April 6, 2018

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

Location: Kulinjanvilla, Alencode Road, Nambali, Tamil Nadu 629154, India

14 comments :

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

    ReplyDelete
    Replies
    1. Thanks for your comment. I'll rectify the anomalies.

      Delete
    2. Client source code updated. Thanks for commenting.

      Delete
  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. This comment has been removed by the author.

    ReplyDelete
  4. 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
  5. How can I use this on pcs connected to different network??? I googled it but can't find any acceptable solution.

    ReplyDelete
  6. 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
  7. 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