-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
88 lines (62 loc) · 2.28 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# Importing Modules
import socket
import threading
from dotenv import load_dotenv
from os import getenv
# Server processing class
class process:
def __init__(self):
load_dotenv()
# Server details
self.HOST = "0.0.0.0"
self.PORT = 1234
# DB details
self.DB_HOST = "localhost"
self.DB = "rsa_pychat"
self.DB_USER = "rsa_pychat"
self.DB_PASS = getenv("DBPASS")
self.connections = []
def listening(self):
while True:
message = self.client.recv(2048).decode("utf-8")
if message != "":
self.message = self.username + "~" + message
self.broadcast()
else:
print(f"Message recieved from {self.username} is empty")
def direct_message(self):
self.client.sendall(self.message.encode("utf-8"))
def broadcast(self):
for user in self.connections:
self.client = user[1]
self.direct_message()
def handle_client(self):
while True:
self.username = self.client.recv(2048).decode("utf-8")
# New user
if self.username != "":
self.connections.append((self.username, self.client))
self.message = "SERVER~" + f"{self.username} has joined the chat"
self.broadcast()
break
else:
self.client.send("Username empty".encode("utf-8"))
thread = threading.Thread(target=self.listening)
thread.start()
def main(self):
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
server.bind((self.HOST, self.PORT))
print(f"Running on {self.HOST}:{self.PORT}")
except socket.error as msg:
print('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
server.listen()
while True:
self.client, address = server.accept()
print(f"Connected to {address}")
thread = threading.Thread(target=self.handle_client)
thread.start()
print(f"Active connections {threading.activeCount() - 1}")
if __name__ == "__main__":
m = process()
m.main()