for python on windows and two files, client and server file Design a Chat applic
ID: 3779369 • Letter: F
Question
for python on windows and two files, client and server file
Design a Chat application which has following features:
o It should use connection orient reliable Transport layer protocol o Chat Application follows client and multithreaded server architecture o Chat Room: Chat Messages are sent from everybody to everybody. o Standard message header: Notice that use of standard header will make applications developed by different users to be compatible with each other. Note that messages in only below format will be exchanged between server and client. Your application header must follow following field structure in the order of appearance. Following is the header structure in tuple format (Header Field, Header Size, description) UNameL, 2 Bytes, Length of username in bytes MessageL, 4 bytes, Length of message Username, n, Username Message, n, Message o Client Side User given parameters: IP address, port number, Username Note: any one is able to connect to any server
o Clients can come and go, when a new client (user) arrives the server should broadcast a message to all the clients with a message that someone has logged in and broadcast a message if server realizes someone has left. Server periodically displays a list of users
Explanation / Answer
import socket, select
def broadcast_data (sock, message):
for socket in CONNECTION_LIST:
if socket != server_socket and socket != sock :
try :
socket.send(message)
except :
socket.close()
CONNECTION_LIST.remove(socket)
if name == "__main__":
CONNECTION_LIST = []
RECV_BUFFER = 4096
PORT = 5000
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM
server_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR, 1)
server_socket.bind(("0.0.0.0", PORT))
server_socket.listen(10)
CONNECTION_LIST.append(server_socket)
print "Chat server started on port " + str(PORT)
while 1:
read_sockets,write_sockets,error_sockets = select.select(CONNECTION_LIST,[],[])
for sock in read_sockets:
if sock == server_socket:
sockfd, addr = server_socket.accept()
CONNECTION_LIST.append(sockfd)
print "Client (%s, %s) connected" % addr
broadcast_data(sockfd, "[%s:%s] entered room " % addr)
else:
try:
data = sock.recv(RECV_BUFFER)
if data:
broadcast_data(sock, " " + '<' + str(sock.getpeername()) + '> ' + data)
except:
broadcast_data(sock, "Client (%s, %s) is offline" % addr)
print "Client (%s, %s) is offline" % addr
sock.close()
CONNECTION_LIST.remove(sock)
continue
server_socket.close()
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.