-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathmultiChatServer.py
More file actions
61 lines (50 loc) · 1.99 KB
/
multiChatServer.py
File metadata and controls
61 lines (50 loc) · 1.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
""" Script for TCP chat server - relays messages to all clients """
from socket import AF_INET, socket, SOCK_STREAM
from threading import Thread
clients = {}
addresses = {}
HOST = "127.0.0.1"
PORT = 5000
BUFSIZ = 1024
ADDR = (HOST, PORT)
SOCK = socket(AF_INET, SOCK_STREAM)
SOCK.bind(ADDR)
def accept_incoming_connections():
"""Sets up handling for incoming clients."""
while True:
client, client_address = SOCK.accept()
print("%s:%s has connected." % client_address)
client.send("Greetings from the ChatRoom! ".encode("utf8"))
client.send("Now type your name and press enter!".encode("utf8"))
addresses[client] = client_address
Thread(target=handle_client, args=(client, client_address)).start()
def handle_client(conn, addr): # Takes client socket as argument.
"""Handles a single client connection."""
name = conn.recv(BUFSIZ).decode("utf8")
welcome = 'Welcome %s! If you ever want to quit, type #quit to exit.' % name
conn.send(bytes(welcome, "utf8"))
msg = "%s from [%s] has joined the chat!" % (name, "{}:{}".format(addr[0], addr[1]))
broadcast(bytes(msg, "utf8"))
clients[conn] = name
while True:
msg = conn.recv(BUFSIZ)
if msg != bytes("#quit", "utf8"):
broadcast(msg, name + ": ")
else:
conn.send(bytes("#quit", "utf8"))
conn.close()
del clients[conn]
broadcast(bytes("%s has left the chat." % name, "utf8"))
break
def broadcast(msg, prefix=""): # prefix is for name identification.
"""Broadcasts a message to all the clients."""
for sock in clients:
sock.send(bytes(prefix, "utf8") + msg)
if __name__ == "__main__":
SOCK.listen(5) # Listens for 5 connections at max.
print("Chat Server has Started !!")
print("Waiting for connections...")
ACCEPT_THREAD = Thread(target=accept_incoming_connections)
ACCEPT_THREAD.start() # Starts the infinite loop.
ACCEPT_THREAD.join()
SOCK.close()