-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimport socket.py
56 lines (43 loc) · 1.58 KB
/
import socket.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
import socket
import threading
import math
import time
last_received_message = ""
def handle_client(connection, client_address):
global last_received_message
try:
print('Connection from', client_address)
# Send the last received message to the new client
if last_received_message:
connection.sendall(last_received_message.encode())
while True:
data = connection.recv(1024).decode()
if not data:
break
print('Received:', data)
# Update the last received message
last_received_message = data
# Broadcast the message to all clients except the sender
for conn in client_connections:
if conn != connection:
conn.sendall(data.encode())
finally:
# Remove the client connection when it's closed
client_connections.remove(connection)
connection.close()
# List to store all client connections
client_connections = []
# Function to start the server
def start_server():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('192.168.123.35', 704)
server_socket.bind(server_address)
server_socket.listen(15)
print('ESPA-X server is listening on', server_address)
while True:
connection, client_address = server_socket.accept()
client_connections.append(connection)
client_thread = threading.Thread(target=handle_client, args=(connection, client_address))
client_thread.start()
# Start the server
start_server()