-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
49 lines (39 loc) · 1.41 KB
/
server.py
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
import socket
import threading
import sys
server_ip = socket.gethostbyname(socket.gethostname())
port = 6969
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((server_ip, port))
server.listen(21)
class User:
current_users = []
def __init__(self, user, user_port, username):
User.current_users.append(self)
self.user = user
self.user_port = user_port
self.user_ip = user.getsockname()[0]
self.username = username
def listen(self):
self.user.send("Welcome to thunderChat!".encode('utf-8'))
self.broadcast(f"{self.username} entered the chat !!")
while True:
try:
message = self.user.recv(2048).decode('utf-8')
if message:
curr_message = f"<{self.username}> : {message}"
self.broadcast(curr_message)
except ConnectionResetError:
User.current_users.remove(self)
break
def broadcast(self, message):
for user in User.current_users:
if user != self:
user.user.send(message.encode('utf-8'))
while True:
user, user_port = server.accept()
username = user.recv(2048).decode('utf-8')
new_user = User(user, user_port, username)
print(f"{username} entered the chat !!")
curr_user_thread = threading.Thread(target=new_user.listen)
curr_user_thread.start()