ๅฐŠๆ•ฌ็š„ ๅพฎไฟกๆฑ‡็Ž‡๏ผš1ๅ†† โ‰ˆ 0.046166 ๅ…ƒ ๆ”ฏไป˜ๅฎๆฑ‡็Ž‡๏ผš1ๅ†† โ‰ˆ 0.046257ๅ…ƒ [้€€ๅ‡บ็™ปๅฝ•]
SlideShare a Scribd company logo
Simple Chat Room using Python
This article demonstrates โ€“ How to set up a simple Chat Room
server and allow multiple clients to connect to it using a client-
side script. The code uses the concept of sockets and threading.
Socket programming
Sockets can be thought of as endpoints in a communication
channel that is bi-directional, and establishes communication
between a server and one or more clients. Here, we set up a
socket on each end and allow a client to interact with other
clients via the server. The socket on the server side associates
itself with some hardware port on the server side. Any client that
has a socket associated with the same port can communicate
with the server socket.
Multi-Threading
A thread is sub process that runs a set of commands individually
of any other thread. So, every time a user connects to the
server, a separate thread is created for that user and
communication from server to client takes place along individual
threads based on socket objects created for the sake of identity
of each client.
We will require two scripts to establish this chat room. One to
keep the serving running, and another that every client should
run in order to connect to the server.
Server Side Script
The server side script will attempt to establish a socket and bind
it to an IP address and port specified by the user (windows users
might have to make an exception for the specified port number
in their firewall settings, or can rather use a port that is already
open). The script will then stay open and receive connection
requests, and will append respective socket objects to a list to
keep track of active connections. Every time a user connects,
a separate thread will be created for that user. In each thread,
the server awaits a message, and sends that message to other
users currently on the chat. If the server encounters an error
while trying to receive a message from a particular thread, it will
exit that thread.
Usage
This server can be set up on a local area network by choosing
any on computer to be a server node, and using that computerโ€™s
private IP address as the server IP address.
For example, if a local area network has a set of private IP
addresses assigned ranging from 192.168.1.2 to 192.168.1.100,
then any computer from these 99 nodes can act as a server, and
the remaining nodes may connect to the server node by using
the serverโ€™s private IP address. Care must be taken to choose a
port that is currently not in usage. For example, port 22 is default
for ssh, and port 80 is default for HTTP protocols. So these two
ports preferably, shouldnt be used or reconfigured to make them
free for usage.
However, if the server is meant to be accessible beyond a local
network, the public IP address would be required for usage. This
would require port forwarding in cases where a node from a local
network (node that isnt the router) wishes to host the server. In
this case, we would require any requests that come to the public
IP addresses to be re routed towards our private IP address in
our local network, and would hence require port forwarding.
To run the script, simply download it from the GitHub link
specified at the bottom of the post, and save it at a convenient
location on your computer.
Usage
This server can be set up on a local area network by choosing
any on computer to be a server node, and using that
computerโ€™s private IP address as the server IP address.
For example, if a local area network has a set of private IP
addresses assigned ranging from 192.168.1.2 to
192.168.1.100, then any computer from these 99 nodes can
act as a server, and the remaining nodes may connect to the
server node by using the serverโ€™s private IP address. Care
must be taken to choose a port that is currently not in usage.
For example, port 22 is default for ssh, and port 80 is default
for HTTP protocols. So these two ports preferably, shouldnโ€™t
be used or reconfigured to make them free for usage.
However, if the server is meant to be accessible beyond a
local network, the public IP address would be required for
usage. This would require port forwarding in cases where a
node from a local network (node that isnt the router) wishes to
host the server. In this case, we would require any requests
that come to the public IP addresses to be re routed towards
our private IP address in our local network, and would hence
require port forwarding.
To run the script, simply download it from the Get Hub link
specified at the bottom of the post, and save it at a convenient
location on your computer.
/* Both the server and client script can then be run
from the Command prompt (in Windows) or from bash
Terminal (Linux users) by simply typing
"python chat_server.py " or "python client.py ".
For example, */
python chat_server.py 192.168.55.13 8081
python client.py 192.168.55.13 8081
Below is the Server side script that must be run at all times to
keep the chat room running.
Filter none
edit
play_ arrow
brightness_4
# Python program to implement server side of chat room.
import socket
import select
import sys
from thread import *
"""The first argument AF_INET is the address domain of the
socket. This is used when we have an Internet Domain with
any two hosts The second argument is the type of socket.
SOCK_STREAM means that data or characters are read in
a continuous flow."""
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# checks whether sufficient arguments have been provided
if len(sys.argv) != 3:
print "Correct usage: script, IP address, port number"
exit()
# takes the first argument from command prompt as IP address
IP_address = str(sys.argv[1])
# takes second argument from command prompt as port number
Port = int(sys.argv[2])
"""
binds the server to an entered IP address and at the
specified port number.
The client must be aware of these parameters
"""
server.bind((IP_address, Port))
"""
listens for 100 active connections. This number can be
increased as per convenience.
"""
server.listen(100)
list_of_clients = []
def clientthread(conn, addr):
# sends a message to the client whose user object is conn
conn.send("Welcome to this chatroom!")
while True:
try:
message = conn.recv(2048)
if message:
"""prints the message and address of the
user who just sent the message on the server
terminal"""
print "<" + addr[0] + "> " + message
# Calls broadcast function to send message to all
message_to_send = "<" + addr[0] + "> " + message
broadcast(message_to_send, conn)
else:
"""message may have no content if the connection
is broken, in this case we remove the connection"""
remove(conn)
except:
continue
"""Using the below function, we broadcast the message to all
clients who's object is not the same as the one sending
the message """
def broadcast(message, connection):
for clients in list_of_clients:
if clients!=connection:
try:
clients.send(message)
except:
clients.close()
# if the link is broken, we remove the client
remove(clients)
"""The following function simply removes the object
from the list that was created at the beginning of
the program"""
def remove(connection):
if connection in list_of_clients:
list_of_clients.remove(connection)
while True:
"""Accepts a connection request and stores two parameters,
conn which is a socket object for that user, and addr
which contains the IP address of the client that just
connected"""
conn, addr = server.accept()
"""Maintains a list of clients for ease of broadcasting
a message to all available people in the chatroom"""
list_of_clients.append(conn)
# prints the address of the user that just connected
print addr[0] + " connected"
# creates and individual thread for every user
# that connects
start_new_thread(clientthread,(conn,addr))
conn.close()
server.close()
Client Side Script
The client side script will simply attempt to access the server
socket created at the specified IP address and port. Once it
connects, it will continuously check as to whether the input
comes from the server or from the client, and accordingly
redirects output. If the input is from the server, it displays the
message on the terminal. If the input is from the user, it sends
the message that the users enters to the server for it to be
broadcasted to other users.
This is the client side script, that each user must use in order to
connect to the server.
filter_ none
edit
play_ arrow
brightness_4
# Python program to implement client side of chat room.
import socket
import select
import sys
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if len(sys.argv) != 3:
print "Correct usage: script, IP address, port number"
exit()
IP_address = str(sys.argv[1])
Port = int(sys.argv[2])
server.connect((IP_address, Port))
while True:
# maintains a list of possible input streams
sockets_list = [sys.stdin, server]
""" There are two possible input situations. Either the
user wants to give manual input to send to other people,
or the server is sending a message to be printed on the
screen. Select returns from sockets_list, the stream that
is reader for input. So for example, if the server wants
to send a message, then the if condition will hold true
below.If the user wants to send a message, the else
condition will evaluate as true"""
read_sockets,write_socket, error_socket = select.select(sockets_list,[],[])
for socks in read_sockets:
if socks == server:
message = socks.recv(2048)
print message
else:
message = sys.stdin.readline()
server.send(message)
sys.stdout.write("<You>")
sys.stdout.write(message)
sys.stdout.flush()
server.close()
Output: In the picture given below, a server has been initialized
on the left side of the terminal and a client script on the right side
of the terminal.
(Splitting of terminal done using tmux, โ€˜sudo apt-get install
tmuxโ€™). For
initialization purposes, you can see that whenever a message is
sent by a user, the message along with IP address is shown on
the server side.
The below picture has a basic conversation between two people
on the same server. Multiple clients can connect to the server in
the same way,
Simple chat room using python

More Related Content

What's hot

Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
kamal kotecha
ย 
Network address translation
Network address translationNetwork address translation
Network address translation
Varsha Honde
ย 
x.509-Directory Authentication Service
x.509-Directory Authentication Servicex.509-Directory Authentication Service
x.509-Directory Authentication Service
Swathy T
ย 
Osi model
Osi modelOsi model
Osi model
Priyanka Sharma
ย 
Chat Application
Chat ApplicationChat Application
Chat Application
kuldip kumar
ย 
Applets in java
Applets in javaApplets in java
Applets in java
Wani Zahoor
ย 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
CEC Landran
ย 
designandimplementanetwork
designandimplementanetworkdesignandimplementanetwork
designandimplementanetwork
Adi Fang
ย 
Distance Vector Routing Protocols
Distance Vector Routing ProtocolsDistance Vector Routing Protocols
Distance Vector Routing Protocols
KABILESH RAMAR
ย 
Firewall & its configurations
Firewall & its configurationsFirewall & its configurations
Firewall & its configurations
Student
ย 
Android async task
Android async taskAndroid async task
Android async task
Madhu Venkat
ย 
Java Networking
Java NetworkingJava Networking
Java Networking
Sunil OS
ย 
Chat application
Chat applicationChat application
Chat application
Mudasir Sunasara
ย 
OS - Process Concepts
OS - Process ConceptsOS - Process Concepts
OS - Process Concepts
Mukesh Chinta
ย 
Packet Tracer Tutorial # 1
Packet Tracer Tutorial # 1Packet Tracer Tutorial # 1
Packet Tracer Tutorial # 1
Abdul Basit
ย 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
Tanmoy Barman
ย 
Lan chat system
Lan chat systemLan chat system
Lan chat system
Wipro
ย 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
VisualBee.com
ย 
Multicast chat with file and desktop sharing
Multicast chat with file and desktop sharingMulticast chat with file and desktop sharing
Multicast chat with file and desktop sharing
Khagendra Chapre
ย 
Electronic mail - Computer Networks
Electronic mail - Computer NetworksElectronic mail - Computer Networks
Electronic mail - Computer Networks
Umme Jamal
ย 

What's hot (20)

Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
ย 
Network address translation
Network address translationNetwork address translation
Network address translation
ย 
x.509-Directory Authentication Service
x.509-Directory Authentication Servicex.509-Directory Authentication Service
x.509-Directory Authentication Service
ย 
Osi model
Osi modelOsi model
Osi model
ย 
Chat Application
Chat ApplicationChat Application
Chat Application
ย 
Applets in java
Applets in javaApplets in java
Applets in java
ย 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
ย 
designandimplementanetwork
designandimplementanetworkdesignandimplementanetwork
designandimplementanetwork
ย 
Distance Vector Routing Protocols
Distance Vector Routing ProtocolsDistance Vector Routing Protocols
Distance Vector Routing Protocols
ย 
Firewall & its configurations
Firewall & its configurationsFirewall & its configurations
Firewall & its configurations
ย 
Android async task
Android async taskAndroid async task
Android async task
ย 
Java Networking
Java NetworkingJava Networking
Java Networking
ย 
Chat application
Chat applicationChat application
Chat application
ย 
OS - Process Concepts
OS - Process ConceptsOS - Process Concepts
OS - Process Concepts
ย 
Packet Tracer Tutorial # 1
Packet Tracer Tutorial # 1Packet Tracer Tutorial # 1
Packet Tracer Tutorial # 1
ย 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
ย 
Lan chat system
Lan chat systemLan chat system
Lan chat system
ย 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
ย 
Multicast chat with file and desktop sharing
Multicast chat with file and desktop sharingMulticast chat with file and desktop sharing
Multicast chat with file and desktop sharing
ย 
Electronic mail - Computer Networks
Electronic mail - Computer NetworksElectronic mail - Computer Networks
Electronic mail - Computer Networks
ย 

Similar to Simple chat room using python

Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docxProject Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
kacie8xcheco
ย 
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
hanneloremccaffery
ย 
Linux Systems Prograramming: Unix Domain, Internet Domain (TCP, UDP) Socket P...
Linux Systems Prograramming: Unix Domain, Internet Domain (TCP, UDP) Socket P...Linux Systems Prograramming: Unix Domain, Internet Domain (TCP, UDP) Socket P...
Linux Systems Prograramming: Unix Domain, Internet Domain (TCP, UDP) Socket P...
RashidFaridChishti
ย 
A.java
A.javaA.java
A.java
JahnaviBhagat
ย 
Networking Java Socket Programming
Networking Java Socket ProgrammingNetworking Java Socket Programming
Networking Java Socket Programming
Mousmi Pawar
ย 
692015 programmingย assignmentย 1ย buildingย aย multiยญthreadedย w
692015 programmingย assignmentย 1ย buildingย aย multiยญthreadedย w692015 programmingย assignmentย 1ย buildingย aย multiยญthreadedย w
692015 programmingย assignmentย 1ย buildingย aย multiยญthreadedย w
smile790243
ย 
Md13 networking
Md13 networkingMd13 networking
Md13 networking
Rakesh Madugula
ย 
Python networking
Python networkingPython networking
1)Building a MultiThreaded Web ServerIn this lab we will devel
1)Building a MultiThreaded Web ServerIn this lab we will devel1)Building a MultiThreaded Web ServerIn this lab we will devel
1)Building a MultiThreaded Web ServerIn this lab we will devel
AgripinaBeaulieuyw
ย 
Application programming interface sockets
Application programming interface socketsApplication programming interface sockets
Application programming interface sockets
Kamran Ashraf
ย 
Mail Server Project Report
Mail Server Project ReportMail Server Project Report
Mail Server Project Report
Kavita Sharma
ย 
Socket
SocketSocket
Socket
Amandeep Kaur
ย 
How a network connection is created A network connection is initi.pdf
How a network connection is created A network connection is initi.pdfHow a network connection is created A network connection is initi.pdf
How a network connection is created A network connection is initi.pdf
arccreation001
ย 
Java Network Programming.pptx
Java Network Programming.pptxJava Network Programming.pptx
Java Network Programming.pptx
RoshniSundrani
ย 
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmenMCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
VannaSchrader3
ย 
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docxMCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
alfredacavx97
ย 
Unit 8 Java
Unit 8 JavaUnit 8 Java
Unit 8 Java
arnold 7490
ย 
java networking
 java networking java networking
java networking
Waheed Warraich
ย 
Net Programming.ppt
Net Programming.pptNet Programming.ppt
Net Programming.ppt
EloAcubaOgardo
ย 
Network Prog.ppt
Network Prog.pptNetwork Prog.ppt
Network Prog.ppt
EloOgardo
ย 

Similar to Simple chat room using python (20)

Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docxProject Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
ย 
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
ย 
Linux Systems Prograramming: Unix Domain, Internet Domain (TCP, UDP) Socket P...
Linux Systems Prograramming: Unix Domain, Internet Domain (TCP, UDP) Socket P...Linux Systems Prograramming: Unix Domain, Internet Domain (TCP, UDP) Socket P...
Linux Systems Prograramming: Unix Domain, Internet Domain (TCP, UDP) Socket P...
ย 
A.java
A.javaA.java
A.java
ย 
Networking Java Socket Programming
Networking Java Socket ProgrammingNetworking Java Socket Programming
Networking Java Socket Programming
ย 
692015 programmingย assignmentย 1ย buildingย aย multiยญthreadedย w
692015 programmingย assignmentย 1ย buildingย aย multiยญthreadedย w692015 programmingย assignmentย 1ย buildingย aย multiยญthreadedย w
692015 programmingย assignmentย 1ย buildingย aย multiยญthreadedย w
ย 
Md13 networking
Md13 networkingMd13 networking
Md13 networking
ย 
Python networking
Python networkingPython networking
Python networking
ย 
1)Building a MultiThreaded Web ServerIn this lab we will devel
1)Building a MultiThreaded Web ServerIn this lab we will devel1)Building a MultiThreaded Web ServerIn this lab we will devel
1)Building a MultiThreaded Web ServerIn this lab we will devel
ย 
Application programming interface sockets
Application programming interface socketsApplication programming interface sockets
Application programming interface sockets
ย 
Mail Server Project Report
Mail Server Project ReportMail Server Project Report
Mail Server Project Report
ย 
Socket
SocketSocket
Socket
ย 
How a network connection is created A network connection is initi.pdf
How a network connection is created A network connection is initi.pdfHow a network connection is created A network connection is initi.pdf
How a network connection is created A network connection is initi.pdf
ย 
Java Network Programming.pptx
Java Network Programming.pptxJava Network Programming.pptx
Java Network Programming.pptx
ย 
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmenMCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
ย 
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docxMCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
ย 
Unit 8 Java
Unit 8 JavaUnit 8 Java
Unit 8 Java
ย 
java networking
 java networking java networking
java networking
ย 
Net Programming.ppt
Net Programming.pptNet Programming.ppt
Net Programming.ppt
ย 
Network Prog.ppt
Network Prog.pptNetwork Prog.ppt
Network Prog.ppt
ย 

More from VISHAL VERMA

srml hr hr sec school
srml hr hr sec schoolsrml hr hr sec school
srml hr hr sec school
VISHAL VERMA
ย 
Project report
Project reportProject report
Project report
VISHAL VERMA
ย 
The text for the handwritten declaration sbi
The text for the handwritten declaration sbiThe text for the handwritten declaration sbi
The text for the handwritten declaration sbi
VISHAL VERMA
ย 
Oriental academy hr school
Oriental academy hr schoolOriental academy hr school
Oriental academy hr school
VISHAL VERMA
ย 
Luthra academy school
Luthra academy schoolLuthra academy school
Luthra academy school
VISHAL VERMA
ย 
Cytotoxic reaction
Cytotoxic reactionCytotoxic reaction
Cytotoxic reaction
VISHAL VERMA
ย 
Sugar industry in india
Sugar industry in indiaSugar industry in india
Sugar industry in india
VISHAL VERMA
ย 
Met gala 2017 dresses
Met gala 2017 dressesMet gala 2017 dresses
Met gala 2017 dresses
VISHAL VERMA
ย 
Met gala 2017 dresses 3
Met gala 2017 dresses  3Met gala 2017 dresses  3
Met gala 2017 dresses 3
VISHAL VERMA
ย 
Met gala 2017 dresses 2
Met gala 2017 dresses  2Met gala 2017 dresses  2
Met gala 2017 dresses 2
VISHAL VERMA
ย 
Chemistry project food adulteration
Chemistry project food adulterationChemistry project food adulteration
Chemistry project food adulteration
VISHAL VERMA
ย 
Caffiene
CaffieneCaffiene
Caffiene
VISHAL VERMA
ย 
Mansar lake
Mansar lakeMansar lake
Mansar lake
VISHAL VERMA
ย 
Learning
LearningLearning
Learning
VISHAL VERMA
ย 
Attitude
AttitudeAttitude
Attitude
VISHAL VERMA
ย 
Organiztional behaviour
Organiztional behaviourOrganiztional behaviour
Organiztional behaviour
VISHAL VERMA
ย 
Busniess ethics
Busniess ethicsBusniess ethics
Busniess ethics
VISHAL VERMA
ย 
Shahnaz hussain
Shahnaz  hussainShahnaz  hussain
Shahnaz hussain
VISHAL VERMA
ย 
Electrochemical cell
Electrochemical cellElectrochemical cell
Electrochemical cell
VISHAL VERMA
ย 
Antibiotics
AntibioticsAntibiotics
Antibiotics
VISHAL VERMA
ย 

More from VISHAL VERMA (20)

srml hr hr sec school
srml hr hr sec schoolsrml hr hr sec school
srml hr hr sec school
ย 
Project report
Project reportProject report
Project report
ย 
The text for the handwritten declaration sbi
The text for the handwritten declaration sbiThe text for the handwritten declaration sbi
The text for the handwritten declaration sbi
ย 
Oriental academy hr school
Oriental academy hr schoolOriental academy hr school
Oriental academy hr school
ย 
Luthra academy school
Luthra academy schoolLuthra academy school
Luthra academy school
ย 
Cytotoxic reaction
Cytotoxic reactionCytotoxic reaction
Cytotoxic reaction
ย 
Sugar industry in india
Sugar industry in indiaSugar industry in india
Sugar industry in india
ย 
Met gala 2017 dresses
Met gala 2017 dressesMet gala 2017 dresses
Met gala 2017 dresses
ย 
Met gala 2017 dresses 3
Met gala 2017 dresses  3Met gala 2017 dresses  3
Met gala 2017 dresses 3
ย 
Met gala 2017 dresses 2
Met gala 2017 dresses  2Met gala 2017 dresses  2
Met gala 2017 dresses 2
ย 
Chemistry project food adulteration
Chemistry project food adulterationChemistry project food adulteration
Chemistry project food adulteration
ย 
Caffiene
CaffieneCaffiene
Caffiene
ย 
Mansar lake
Mansar lakeMansar lake
Mansar lake
ย 
Learning
LearningLearning
Learning
ย 
Attitude
AttitudeAttitude
Attitude
ย 
Organiztional behaviour
Organiztional behaviourOrganiztional behaviour
Organiztional behaviour
ย 
Busniess ethics
Busniess ethicsBusniess ethics
Busniess ethics
ย 
Shahnaz hussain
Shahnaz  hussainShahnaz  hussain
Shahnaz hussain
ย 
Electrochemical cell
Electrochemical cellElectrochemical cell
Electrochemical cell
ย 
Antibiotics
AntibioticsAntibiotics
Antibiotics
ย 

Recently uploaded

(T.L.E.) Agriculture: "Ornamental Plants"
(T.L.E.) Agriculture: "Ornamental Plants"(T.L.E.) Agriculture: "Ornamental Plants"
(T.L.E.) Agriculture: "Ornamental Plants"
MJDuyan
ย 
managing Behaviour in early childhood education.pptx
managing Behaviour in early childhood education.pptxmanaging Behaviour in early childhood education.pptx
managing Behaviour in early childhood education.pptx
nabaegha
ย 
220711130082 Srabanti Bag Internet Resources For Natural Science
220711130082 Srabanti Bag Internet Resources For Natural Science220711130082 Srabanti Bag Internet Resources For Natural Science
220711130082 Srabanti Bag Internet Resources For Natural Science
Kalna College
ย 
nutrition in plants chapter 1 class 7...
nutrition in plants chapter 1 class 7...nutrition in plants chapter 1 class 7...
nutrition in plants chapter 1 class 7...
chaudharyreet2244
ย 
Information and Communication Technology in Education
Information and Communication Technology in EducationInformation and Communication Technology in Education
Information and Communication Technology in Education
MJDuyan
ย 
Slides Peluncuran Amalan Pemakanan Sihat.pptx
Slides Peluncuran Amalan Pemakanan Sihat.pptxSlides Peluncuran Amalan Pemakanan Sihat.pptx
Slides Peluncuran Amalan Pemakanan Sihat.pptx
shabeluno
ย 
Cross-Cultural Leadership and Communication
Cross-Cultural Leadership and CommunicationCross-Cultural Leadership and Communication
Cross-Cultural Leadership and Communication
MattVassar1
ย 
Erasmus + DISSEMINATION ACTIVITIES Croatia
Erasmus + DISSEMINATION ACTIVITIES CroatiaErasmus + DISSEMINATION ACTIVITIES Croatia
Erasmus + DISSEMINATION ACTIVITIES Croatia
whatchangedhowreflec
ย 
Post init hook in the odoo 17 ERP Module
Post init hook in the  odoo 17 ERP ModulePost init hook in the  odoo 17 ERP Module
Post init hook in the odoo 17 ERP Module
Celine George
ย 
78 Microsoft-Publisher - Sirin Sultana Bora.pptx
78 Microsoft-Publisher - Sirin Sultana Bora.pptx78 Microsoft-Publisher - Sirin Sultana Bora.pptx
78 Microsoft-Publisher - Sirin Sultana Bora.pptx
Kalna College
ย 
Diversity Quiz Prelims by Quiz Club, IIT Kanpur
Diversity Quiz Prelims by Quiz Club, IIT KanpurDiversity Quiz Prelims by Quiz Club, IIT Kanpur
Diversity Quiz Prelims by Quiz Club, IIT Kanpur
Quiz Club IIT Kanpur
ย 
The basics of sentences session 8pptx.pptx
The basics of sentences session 8pptx.pptxThe basics of sentences session 8pptx.pptx
The basics of sentences session 8pptx.pptx
heathfieldcps1
ย 
A Quiz on Drug Abuse Awareness by Quizzito
A Quiz on Drug Abuse Awareness by QuizzitoA Quiz on Drug Abuse Awareness by Quizzito
A Quiz on Drug Abuse Awareness by Quizzito
Quizzito The Quiz Society of Gargi College
ย 
220711130083 SUBHASHREE RAKSHIT Internet resources for social science
220711130083 SUBHASHREE RAKSHIT  Internet resources for social science220711130083 SUBHASHREE RAKSHIT  Internet resources for social science
220711130083 SUBHASHREE RAKSHIT Internet resources for social science
Kalna College
ย 
bryophytes.pptx bsc botany honours second semester
bryophytes.pptx bsc botany honours  second semesterbryophytes.pptx bsc botany honours  second semester
bryophytes.pptx bsc botany honours second semester
Sarojini38
ย 
Creativity for Innovation and Speechmaking
Creativity for Innovation and SpeechmakingCreativity for Innovation and Speechmaking
Creativity for Innovation and Speechmaking
MattVassar1
ย 
Opportunity scholarships and the schools that receive them
Opportunity scholarships and the schools that receive themOpportunity scholarships and the schools that receive them
Opportunity scholarships and the schools that receive them
EducationNC
ย 
Diversity Quiz Finals by Quiz Club, IIT Kanpur
Diversity Quiz Finals by Quiz Club, IIT KanpurDiversity Quiz Finals by Quiz Club, IIT Kanpur
Diversity Quiz Finals by Quiz Club, IIT Kanpur
Quiz Club IIT Kanpur
ย 
220711130088 Sumi Basak Virtual University EPC 3.pptx
220711130088 Sumi Basak Virtual University EPC 3.pptx220711130088 Sumi Basak Virtual University EPC 3.pptx
220711130088 Sumi Basak Virtual University EPC 3.pptx
Kalna College
ย 
Get Success with the Latest UiPath UIPATH-ADPV1 Exam Dumps (V11.02) 2024
Get Success with the Latest UiPath UIPATH-ADPV1 Exam Dumps (V11.02) 2024Get Success with the Latest UiPath UIPATH-ADPV1 Exam Dumps (V11.02) 2024
Get Success with the Latest UiPath UIPATH-ADPV1 Exam Dumps (V11.02) 2024
yarusun
ย 

Recently uploaded (20)

(T.L.E.) Agriculture: "Ornamental Plants"
(T.L.E.) Agriculture: "Ornamental Plants"(T.L.E.) Agriculture: "Ornamental Plants"
(T.L.E.) Agriculture: "Ornamental Plants"
ย 
managing Behaviour in early childhood education.pptx
managing Behaviour in early childhood education.pptxmanaging Behaviour in early childhood education.pptx
managing Behaviour in early childhood education.pptx
ย 
220711130082 Srabanti Bag Internet Resources For Natural Science
220711130082 Srabanti Bag Internet Resources For Natural Science220711130082 Srabanti Bag Internet Resources For Natural Science
220711130082 Srabanti Bag Internet Resources For Natural Science
ย 
nutrition in plants chapter 1 class 7...
nutrition in plants chapter 1 class 7...nutrition in plants chapter 1 class 7...
nutrition in plants chapter 1 class 7...
ย 
Information and Communication Technology in Education
Information and Communication Technology in EducationInformation and Communication Technology in Education
Information and Communication Technology in Education
ย 
Slides Peluncuran Amalan Pemakanan Sihat.pptx
Slides Peluncuran Amalan Pemakanan Sihat.pptxSlides Peluncuran Amalan Pemakanan Sihat.pptx
Slides Peluncuran Amalan Pemakanan Sihat.pptx
ย 
Cross-Cultural Leadership and Communication
Cross-Cultural Leadership and CommunicationCross-Cultural Leadership and Communication
Cross-Cultural Leadership and Communication
ย 
Erasmus + DISSEMINATION ACTIVITIES Croatia
Erasmus + DISSEMINATION ACTIVITIES CroatiaErasmus + DISSEMINATION ACTIVITIES Croatia
Erasmus + DISSEMINATION ACTIVITIES Croatia
ย 
Post init hook in the odoo 17 ERP Module
Post init hook in the  odoo 17 ERP ModulePost init hook in the  odoo 17 ERP Module
Post init hook in the odoo 17 ERP Module
ย 
78 Microsoft-Publisher - Sirin Sultana Bora.pptx
78 Microsoft-Publisher - Sirin Sultana Bora.pptx78 Microsoft-Publisher - Sirin Sultana Bora.pptx
78 Microsoft-Publisher - Sirin Sultana Bora.pptx
ย 
Diversity Quiz Prelims by Quiz Club, IIT Kanpur
Diversity Quiz Prelims by Quiz Club, IIT KanpurDiversity Quiz Prelims by Quiz Club, IIT Kanpur
Diversity Quiz Prelims by Quiz Club, IIT Kanpur
ย 
The basics of sentences session 8pptx.pptx
The basics of sentences session 8pptx.pptxThe basics of sentences session 8pptx.pptx
The basics of sentences session 8pptx.pptx
ย 
A Quiz on Drug Abuse Awareness by Quizzito
A Quiz on Drug Abuse Awareness by QuizzitoA Quiz on Drug Abuse Awareness by Quizzito
A Quiz on Drug Abuse Awareness by Quizzito
ย 
220711130083 SUBHASHREE RAKSHIT Internet resources for social science
220711130083 SUBHASHREE RAKSHIT  Internet resources for social science220711130083 SUBHASHREE RAKSHIT  Internet resources for social science
220711130083 SUBHASHREE RAKSHIT Internet resources for social science
ย 
bryophytes.pptx bsc botany honours second semester
bryophytes.pptx bsc botany honours  second semesterbryophytes.pptx bsc botany honours  second semester
bryophytes.pptx bsc botany honours second semester
ย 
Creativity for Innovation and Speechmaking
Creativity for Innovation and SpeechmakingCreativity for Innovation and Speechmaking
Creativity for Innovation and Speechmaking
ย 
Opportunity scholarships and the schools that receive them
Opportunity scholarships and the schools that receive themOpportunity scholarships and the schools that receive them
Opportunity scholarships and the schools that receive them
ย 
Diversity Quiz Finals by Quiz Club, IIT Kanpur
Diversity Quiz Finals by Quiz Club, IIT KanpurDiversity Quiz Finals by Quiz Club, IIT Kanpur
Diversity Quiz Finals by Quiz Club, IIT Kanpur
ย 
220711130088 Sumi Basak Virtual University EPC 3.pptx
220711130088 Sumi Basak Virtual University EPC 3.pptx220711130088 Sumi Basak Virtual University EPC 3.pptx
220711130088 Sumi Basak Virtual University EPC 3.pptx
ย 
Get Success with the Latest UiPath UIPATH-ADPV1 Exam Dumps (V11.02) 2024
Get Success with the Latest UiPath UIPATH-ADPV1 Exam Dumps (V11.02) 2024Get Success with the Latest UiPath UIPATH-ADPV1 Exam Dumps (V11.02) 2024
Get Success with the Latest UiPath UIPATH-ADPV1 Exam Dumps (V11.02) 2024
ย 

Simple chat room using python

  • 1. Simple Chat Room using Python This article demonstrates โ€“ How to set up a simple Chat Room server and allow multiple clients to connect to it using a client- side script. The code uses the concept of sockets and threading. Socket programming Sockets can be thought of as endpoints in a communication channel that is bi-directional, and establishes communication between a server and one or more clients. Here, we set up a socket on each end and allow a client to interact with other clients via the server. The socket on the server side associates itself with some hardware port on the server side. Any client that
  • 2. has a socket associated with the same port can communicate with the server socket. Multi-Threading A thread is sub process that runs a set of commands individually of any other thread. So, every time a user connects to the server, a separate thread is created for that user and communication from server to client takes place along individual threads based on socket objects created for the sake of identity of each client. We will require two scripts to establish this chat room. One to keep the serving running, and another that every client should run in order to connect to the server. Server Side Script The server side script will attempt to establish a socket and bind it to an IP address and port specified by the user (windows users might have to make an exception for the specified port number in their firewall settings, or can rather use a port that is already open). The script will then stay open and receive connection requests, and will append respective socket objects to a list to keep track of active connections. Every time a user connects, a separate thread will be created for that user. In each thread, the server awaits a message, and sends that message to other users currently on the chat. If the server encounters an error while trying to receive a message from a particular thread, it will exit that thread. Usage This server can be set up on a local area network by choosing any on computer to be a server node, and using that computerโ€™s private IP address as the server IP address. For example, if a local area network has a set of private IP addresses assigned ranging from 192.168.1.2 to 192.168.1.100,
  • 3. then any computer from these 99 nodes can act as a server, and the remaining nodes may connect to the server node by using the serverโ€™s private IP address. Care must be taken to choose a port that is currently not in usage. For example, port 22 is default for ssh, and port 80 is default for HTTP protocols. So these two ports preferably, shouldnt be used or reconfigured to make them free for usage. However, if the server is meant to be accessible beyond a local network, the public IP address would be required for usage. This would require port forwarding in cases where a node from a local network (node that isnt the router) wishes to host the server. In this case, we would require any requests that come to the public IP addresses to be re routed towards our private IP address in our local network, and would hence require port forwarding. To run the script, simply download it from the GitHub link specified at the bottom of the post, and save it at a convenient location on your computer. Usage This server can be set up on a local area network by choosing any on computer to be a server node, and using that computerโ€™s private IP address as the server IP address. For example, if a local area network has a set of private IP addresses assigned ranging from 192.168.1.2 to 192.168.1.100, then any computer from these 99 nodes can act as a server, and the remaining nodes may connect to the server node by using the serverโ€™s private IP address. Care must be taken to choose a port that is currently not in usage. For example, port 22 is default for ssh, and port 80 is default for HTTP protocols. So these two ports preferably, shouldnโ€™t be used or reconfigured to make them free for usage. However, if the server is meant to be accessible beyond a local network, the public IP address would be required for usage. This would require port forwarding in cases where a node from a local network (node that isnt the router) wishes to host the server. In this case, we would require any requests
  • 4. that come to the public IP addresses to be re routed towards our private IP address in our local network, and would hence require port forwarding. To run the script, simply download it from the Get Hub link specified at the bottom of the post, and save it at a convenient location on your computer. /* Both the server and client script can then be run from the Command prompt (in Windows) or from bash Terminal (Linux users) by simply typing "python chat_server.py " or "python client.py ". For example, */ python chat_server.py 192.168.55.13 8081 python client.py 192.168.55.13 8081 Below is the Server side script that must be run at all times to keep the chat room running. Filter none edit play_ arrow brightness_4 # Python program to implement server side of chat room. import socket import select import sys from thread import * """The first argument AF_INET is the address domain of the socket. This is used when we have an Internet Domain with any two hosts The second argument is the type of socket. SOCK_STREAM means that data or characters are read in a continuous flow.""" server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # checks whether sufficient arguments have been provided if len(sys.argv) != 3: print "Correct usage: script, IP address, port number" exit() # takes the first argument from command prompt as IP address IP_address = str(sys.argv[1])
  • 5. # takes second argument from command prompt as port number Port = int(sys.argv[2]) """ binds the server to an entered IP address and at the specified port number. The client must be aware of these parameters """ server.bind((IP_address, Port)) """ listens for 100 active connections. This number can be increased as per convenience. """ server.listen(100) list_of_clients = [] def clientthread(conn, addr): # sends a message to the client whose user object is conn conn.send("Welcome to this chatroom!") while True: try: message = conn.recv(2048) if message: """prints the message and address of the user who just sent the message on the server terminal""" print "<" + addr[0] + "> " + message # Calls broadcast function to send message to all message_to_send = "<" + addr[0] + "> " + message broadcast(message_to_send, conn) else: """message may have no content if the connection is broken, in this case we remove the connection""" remove(conn) except: continue """Using the below function, we broadcast the message to all clients who's object is not the same as the one sending the message """ def broadcast(message, connection): for clients in list_of_clients: if clients!=connection: try: clients.send(message) except: clients.close() # if the link is broken, we remove the client remove(clients)
  • 6. """The following function simply removes the object from the list that was created at the beginning of the program""" def remove(connection): if connection in list_of_clients: list_of_clients.remove(connection) while True: """Accepts a connection request and stores two parameters, conn which is a socket object for that user, and addr which contains the IP address of the client that just connected""" conn, addr = server.accept() """Maintains a list of clients for ease of broadcasting a message to all available people in the chatroom""" list_of_clients.append(conn) # prints the address of the user that just connected print addr[0] + " connected" # creates and individual thread for every user # that connects start_new_thread(clientthread,(conn,addr)) conn.close() server.close() Client Side Script The client side script will simply attempt to access the server socket created at the specified IP address and port. Once it connects, it will continuously check as to whether the input comes from the server or from the client, and accordingly redirects output. If the input is from the server, it displays the message on the terminal. If the input is from the user, it sends the message that the users enters to the server for it to be broadcasted to other users. This is the client side script, that each user must use in order to connect to the server. filter_ none edit play_ arrow brightness_4
  • 7. # Python program to implement client side of chat room. import socket import select import sys server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if len(sys.argv) != 3: print "Correct usage: script, IP address, port number" exit() IP_address = str(sys.argv[1]) Port = int(sys.argv[2]) server.connect((IP_address, Port)) while True: # maintains a list of possible input streams sockets_list = [sys.stdin, server] """ There are two possible input situations. Either the user wants to give manual input to send to other people, or the server is sending a message to be printed on the screen. Select returns from sockets_list, the stream that is reader for input. So for example, if the server wants to send a message, then the if condition will hold true below.If the user wants to send a message, the else condition will evaluate as true""" read_sockets,write_socket, error_socket = select.select(sockets_list,[],[]) for socks in read_sockets: if socks == server: message = socks.recv(2048) print message else: message = sys.stdin.readline() server.send(message) sys.stdout.write("<You>") sys.stdout.write(message) sys.stdout.flush() server.close() Output: In the picture given below, a server has been initialized on the left side of the terminal and a client script on the right side of the terminal.
  • 8. (Splitting of terminal done using tmux, โ€˜sudo apt-get install tmuxโ€™). For initialization purposes, you can see that whenever a message is sent by a user, the message along with IP address is shown on the server side. The below picture has a basic conversation between two people on the same server. Multiple clients can connect to the server in the same way,
  ็ฟป่ฏ‘๏ผš