-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
65 lines (55 loc) · 1.88 KB
/
Copy pathserver.py
File metadata and controls
65 lines (55 loc) · 1.88 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
62
63
64
65
import time
import socket
import threading
ip_server = socket.gethostbyname(socket.gethostname())
port = 8080
encoding_format = 'utf-8'
#Create socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((ip_server,port))
connections, messages = [], []
#Handle message
def handle_clientes(conn, addr):
print(f"[INFO] New user are connected with ip address: {addr}")
global connections,messages
name = False
while(True):
msg = conn.recv(1024).decode(encoding_format)
if(msg):
if(msg.startswith("name=")):
split_msg = msg.split("=")
name = split_msg[1]
map_connection = {
"conn": conn,
"addr": addr,
"name": name,
"last": 0
}
connections.append(map_connection)
send_individual_user(map_connection)
elif(msg.startswith("msg=")):
split_msg = msg.split("=")
message = name + "=" + split_msg[1][::-1]
messages.append(message)
send_message_all_users()
#Send message for individual user
def send_individual_user(connection):
print(f"[INFO] Sending message for {connection['addr']}")
for i in range(connection['last'], len(messages)):
message = "msg=" + messages[i]
connection['conn'].send(message.encode())
connection['last'] = i + 1
time.sleep(0.2)
#Send message for all users
def send_message_all_users():
global connections
for connection in connections:
send_individual_user(connection)
def start():
print(f"[INFO] Starting socket with ip addres {ip_server}:{port}")
server.listen()
while(True):
conn, addr = server.accept()
thread = threading.Thread(target=handle_clientes, args=(conn, addr))
thread.start()
start()