Multiuser Chatting using TCP Socket
Program :
Server Side :
import socket
import os
import threading
from threading import Thread
clients_lock = threading.Lock()
names = {}
def listener(client, address):
'''Receive name''' #Receive name of connected client
names[client] = name #Add name to names dictionary
print (names[client]+" joined chat from IP:"+str(address[0])+" and Port:"+str(address[1]))
with clients_lock:
clients.add(client) #Adding client socket value to clients list
#print clients
try:
while True:
'''Receive data''' #Receive data from client
if not data:
break
else:
data = names[client]+":"+str(data) #Append data with client name
#print data
with clients_lock:
for c in clients: #Send the data to all the clients
c.send(data)
finally:
with clients_lock:
clients.remove(client) #If client exit, then remove the client value
client.close()
host = '' #Server IP addres
port = 10015 #Port address
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #Creating a Socket
s.bind((host,port)) #Binding Port and IP address
s.listen(3) #Listen to connection
client, address = s.accept()
th = [] #Array for threads
print ("Server is listening for connections...")
while True:
'''Accept Connection''' #Accept a client connecion
try:
#Launch a thread for each client request
th.append(Thread(target=listener, args = (client,address)).start())
except (KeyboardInterrupt, SystemExit):
cleanup_stop_thread();
s.close() #Closing the socket
sys.exit()
Client Side:
#!/usr/bin/env python
import socket
from threading import Thread, Lock
def receiver(sock):
while flag:
data = sock.recv(size)
print ("\t\t"+data)
host = 'localhost' #Server IP addres
port = 10015 #Port address
size = 1024 #Size of packet data to receive
flag = True
'''Creating a Socket'''
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
'''Connect to Server'''
sock.bind((host,port))
# Start Receiver Thread
hop = Thread(target=receiver, args=(sock,))
hop.daemon = True
hop.start()
data = bytes(input("Enter Message:"), encoding="UTF-8")
sock.send(data)
while data != 'quit': #User will enter 'quit' to exit server
data = bytes(input("Enter Message:"), encoding="UTF-8") #Enter message to send to server
sock.send(data) #Sending data to server
sock.close() #Closing the socket
No comments: