Python program to create a simple chat box.

In this tutorial, we are going to learn about how we can create a simple Python chat box. For this, we will be using the socket module of python. The chat box can be between client to server, client to client or client to itself.

The client is an end device interfacing with human and server is a device which provides service to a client.

Sockets are the programming abstractions or concept for connections. They allow us to communicate in bidirectional manner. So, once they are connected we can use them to send and receive data.
Following are the various socket methods which will be used in your program:

  1. socket(socket_family, socket_type): To create a new socket object.
  2. bind((hostname, port)): Bind to the port.
  3. listen(backlog): Listen for connections made to the socket. The backlog argument specifies the maximum number of queued connections and they should be at least 0; the maximum value is system-dependent (usually 5).
  4. accept(): Accepts a connection when found.
  5.  gethostname(): To get a local machine name.
  6. send(bytes): Attempts to send the bytes given to it.
  7. close(): Closes a socket/connection and release the port.
  8. recv(buffer): Receives data from the connection.

How to make the simple chat box in python

A simple server code:

  1. We will import socket module.
  2. Get the hostname by using hostname() method.
  3. Reserve a port for your service. The port numbers from 1-1024 are reserved for the core protocols. So, the port number for the service can be between 1025-65535.
  4. socket.socket() will create a new socket. s is the socket object in the code.
  5. s.bind() will bind the socket using HOST and PORT.
  6. s.listen(1) will receive one connection at one time. You can increase upto 5 connections at one time.
  7. s.accept() will return a pair of values(conn, addr) where conn will be the new socket object used for sending and receiving the data. addr is the address that is bound to the socket on the other end of the connection.
  8. Create a while loop to receive and send the data. conn.recv(1024) will receive the data with maximum length of 1024 words. conn.send() will send the data.
    sendall() in sever code will send data to the every node connected with the server, if we use send command it will send data to one specific node. To come out of the chat box make a if statement where reply ==’end’.
  9. Close the connection by conn.close().
import socket
print("For server side")
HOST=socket.gethostname()
PORT=12345
s=socket.socket()
s.bind((HOST,PORT))
s.listen(1)
conn,addr=s.accept()
print("connected by:",addr)
while True:
    data=conn.recv(1024)
    print('received',repr(data))
    reply=input("message:")
    conn.sendall(reply.encode())
    if reply=='end':
        break
conn.close()   

A simple client code:

  1. Import the socket module.
  2. Get the hostname by using socket.hostname()
  3. Give the port number, same as the server for bind.
  4. Create the socket object and connect the client to the server through the HOST and PORT.
  5. Make a while loop for sending and receiving the data using s.send() and s.recv() methods respectively. To come out of the chat box make a if statement where message ==’end’.
  6. Close the connection with the help of s.close().
import socket
print("For client side")
HOST=socket.gethostname()
PORT=12345
s=socket.socket()
s.connect((HOST,PORT))
while True:
    message=input("Ur msg: ")
    s.send(message.encode())
    if message=='end':
        break
    reply=s.recv(1024)
    print("Recieved",repr(reply))
s.close()
    

Output:

The output of our program is given below:

For client side
Ur msg: hey
Recieved b'how are you?'
Ur msg: I am fine.
Recieved b'ok'
Ur msg: end
>>>
For server side
connected by: ('127.0.0.1', 63961)
received b'hey'
message:how are you?
received b'I am fine.'
message:ok
received b'end'
message:end
>>> 

Note: Save both the files with .py extension and firstly run the server code then the client code.

Also, read:

 

Leave a Reply

Your email address will not be published. Required fields are marked *