-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.py
100 lines (76 loc) · 2.64 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
89
90
91
92
93
94
95
96
97
98
99
100
from socket import *
import threading
import os
import sys
from colors import print_color, format_string
from connection import set_connection
SERVER_SOCKET = socket(AF_INET, SOCK_STREAM)
CLIENTS = list()
ADDRESSES = list()
USERS = list()
SERVER_IP = ''
SERVER_PORT = 0
def print_connections():
os.system('cls')
print_color(f'\nReady to receive at {SERVER_IP}:{SERVER_PORT}\n', 'green')
if len(ADDRESSES) > 0:
print_color(f'\nCONNECTIONS: \n', 'green')
for address in ADDRESSES:
print_color(f'\tConnected with {address}', 'cyan')
def broadcast(message, sender=None):
for client in CLIENTS:
if client == sender:
continue
client.send(message)
def handle(client):
while True:
try:
message = client.recv(1024)
broadcast(message, client)
except:
index = CLIENTS.index(client)
CLIENTS.remove(client)
client.close()
user = USERS[index]
broadcast(format_string(f'{user} left!', color='red').encode())
USERS.remove(user)
del ADDRESSES[index]
print_connections()
break
def receive():
while True:
connection_socket, addr = SERVER_SOCKET.accept()
connection_socket.send('USER'.encode())
user = connection_socket.recv(1024).decode()
USERS.append(user)
CLIENTS.append(connection_socket)
ADDRESSES.append(addr)
print_connections()
broadcast(f'{user} joined'.encode(), sender=connection_socket)
connection_socket.send(format_string(f'Connected to server!', color='green').encode())
client_thread = threading.Thread(target=handle, args=(connection_socket,))
client_thread.start()
os.system('cls')
print(" _______ _____ _____ _____ \n"
" |__ __/ ____| __ \ / ____| \n"
" | | | | | |__) | | (___ ___ _ ____ _____ _ __ \n"
" | | | | | ___/ \___ \ / _ \ '__\ \ / / _ \ '__| \n"
" | | | |____| | ____) | __/ | \ V / __/ | \n"
" |_| \_____|_| |_____/ \___|_| \_/ \___|_| \n"
)
input("PRESS ENTER TO START")
os.system('cls')
if 'default' in sys.argv:
SERVER_IP = 'localhost'
SERVER_PORT = 12000
else:
SERVER_IP, SERVER_PORT = set_connection()
print_color('\nOpening server...', color='yellow')
try:
SERVER_SOCKET.bind((SERVER_IP, SERVER_PORT))
except OSError as e:
print_color(f'\n{e}', color='red')
exit(-1)
SERVER_SOCKET.listen()
print_color(f'\nReady to receive at {SERVER_IP}:{SERVER_PORT}\n', color='green')
receive()