-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
76 lines (65 loc) · 2.21 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
import socket
from _thread import *
import logging
import colorlog
import os
from dotenv import load_dotenv
def client_handler(connection):
connection.send(
str.encode(
'You are now connected to the replay server... Type BYE to stop'))
client_info = connection.getpeername()
while True:
try:
data = connection.recv(2048)
message = data.decode('utf-8')
if message == 'BYE':
break
else:
logger.debug(f'Client: {message}')
reply = f'Server: {message}'
connection.sendall(str.encode(reply))
except:
logger.error(f"Client disconnected {client_info}")
break
connection.close()
def accept_connections(ServerSocket):
client, address = ServerSocket.accept()
logger.info('Connected to: ' + address[0] + ':' + str(address[1]))
start_new_thread(client_handler, (client, ))
# ______________________________________________________________________________
# Main
# ______________________________________________________________________________
if __name__ == '__main__':
load_dotenv()
# Définir l'adresse IP et le port du serveur
host = os.getenv('MIRADOR_IP') # Adresse IP locale
port = int(os.getenv('MIRADOR_PORT')) # Port arbitraire
# configure logger
handler = colorlog.StreamHandler()
formatter = colorlog.ColoredFormatter(
"%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s",
datefmt=None,
reset=True,
log_colors={
'DEBUG': 'cyan',
'INFO': 'green',
'WARNING': 'yellow',
'ERROR': 'red',
'CRITICAL': 'red,bg_white',
},
secondary_log_colors={},
style='%')
handler.setFormatter(formatter)
logger = colorlog.getLogger(__name__)
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
ServerSocket = socket.socket()
try:
ServerSocket.bind((host, port))
except socket.error as e:
print(str(e))
logger.info(f'Server is listing on the port {port}...')
ServerSocket.listen()
while True:
accept_connections(ServerSocket)