visit
Python is one of the most versatile programming languages and one can observe that through its various applications everywhere. Here is an example of how you can build a simple command-line based chat room using python which is easy to implement and understand. So let’s get started.
A chat room is a medium/interface that allows two or more people to chat and send messages to everyone. It can be interpersonal (one-one) and group chat too. In this tutorial, we’re going to build a group chat room that can host more than two clients at a time.
While defining socket, two parameters named (AF_INET) and (SOCK_STREAM) will be used. First one indicates the usage of internet socket and the other one indicates the usage of TCP. Then we move on by defining the broadcast function. Its basic function is to send message to the clients in the clients list. This function is not retiring yet. We are going to use it ahead in other places too. Handling the clients is a pretty tough job, so is the function. It first tries if a message can be received from the client’s end, if yes, it is broadcasted.
But if there’s any kind of error/issue, the server keeps things simple. It simply removes the client. We’ve done a lot of work but, adding the clients still awaits. So let’s do that now. In the receive function, the keyword ‘NICKNAME’ is sent to the clients which means their nickname is requested. Later upon obtaining the nickname, it adds the client to the list. Well, this loop remains active and multiple clients can join the server. All that you need to have it the right IP and the port address.Code:#Coded by Yashraj Singh Chouhan
import socket, threading #Libraries import
host = '127.0.0.1' #LocalHost
port = 7976 #Choosing unreserved port
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #socket initialization
server.bind((host, port)) #binding host and port to socket
server.listen()
clients = []
nicknames = []
def broadcast(message): #broadcast function declaration
for client in clients:
client.send(message)
def handle(client):
while True:
try: #recieving valid messages from client
message = client.recv(1024)
broadcast(message)
except: #removing clients
index = clients.index(client)
clients.remove(client)
client.close()
nickname = nicknames[index]
broadcast('{} left!'.format(nickname).encode('ascii'))
nicknames.remove(nickname)
break
def receive(): #accepting multiple clients
while True:
client, address = server.accept()
print("Connected with {}".format(str(address)))
client.send('NICKNAME'.encode('ascii'))
nickname = client.recv(1024).decode('ascii')
nicknames.append(nickname)
clients.append(client)
print("Nickname is {}".format(nickname))
broadcast("{} joined!".format(nickname).encode('ascii'))
client.send('Connected to server!'.encode('ascii'))
thread = threading.Thread(target=handle, args=(client,))
thread.start()
receive()
#Coded by Yashraj Singh Chouhan
import socket, threading
nickname = input("Choose your nickname: ")
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #socket initialization
client.connect(('127.0.0.1', 7976)) #connecting client to server
def receive():
while True: #making valid connection
try:
message = client.recv(1024).decode('ascii')
if message == 'NICKNAME':
client.send(nickname.encode('ascii'))
else:
print(message)
except: #case on wrong ip/port details
print("An error occured!")
client.close()
break
def write():
while True: #message layout
message = '{}: {}'.format(nickname, input(''))
client.send(message.encode('ascii'))
receive_thread = threading.Thread(target=receive) #receiving multiple messages
receive_thread.start()
write_thread = threading.Thread(target=write) #sending messages
write_thread.start()