|
1 |
| -import socket, _thread |
| 1 | +import socket, threading |
2 | 2 |
|
| 3 | +# Global variable that mantain client's connections |
3 | 4 | connections = []
|
4 | 5 |
|
5 | 6 | def handle_user_connection(connection: socket.socket, address: str) -> None:
|
| 7 | + ''' |
| 8 | + Get user connection in order to keep receiving their messages and |
| 9 | + sent to others users/connections. |
| 10 | + ''' |
6 | 11 | while True:
|
7 | 12 | try:
|
8 |
| - msg = connection.recv(1024).decode() |
| 13 | + # Get client message |
| 14 | + msg = connection.recv(1024) |
9 | 15 |
|
| 16 | + # If no message is received, there is a chance that connection has ended |
| 17 | + # so in this case, we need to close connection and remove it from connections list. |
10 | 18 | if msg:
|
11 |
| - print(f'{address[0]}:{address[1]} - {msg}') |
12 |
| - |
13 |
| - msg_to_send = f'From {address[0]}:{address[1]} - {msg}' |
14 |
| - |
| 19 | + # Log message sent by user |
| 20 | + print(f'{address[0]}:{address[1]} - {msg.decode()}') |
| 21 | + |
| 22 | + # Build message format and broadcast to users connected on server |
| 23 | + msg_to_send = f'From {address[0]}:{address[1]} - {msg.decode()}' |
15 | 24 | broadcast(msg_to_send, connection)
|
| 25 | + |
| 26 | + # Close connection if no message was sent |
16 | 27 | else:
|
17 | 28 | remove_connection(connection)
|
18 | 29 | break
|
| 30 | + |
19 | 31 | except Exception as e:
|
20 | 32 | print(f'Error to handle user connection: {e}')
|
21 | 33 | remove_connection(connection)
|
22 | 34 | break
|
23 | 35 |
|
24 | 36 |
|
25 | 37 | def broadcast(message: str, connection: socket.socket) -> None:
|
| 38 | + ''' |
| 39 | + Broadcast message to all users connected to the server |
| 40 | + ''' |
| 41 | + |
| 42 | + # Iterate on connections in order to send message to all client's connected |
26 | 43 | for client_conn in connections:
|
| 44 | + # Check if isn't the connection of who's send |
27 | 45 | if client_conn != connection:
|
28 | 46 | try:
|
| 47 | + # Sending message to client connection |
29 | 48 | client_conn.send(message.encode())
|
30 |
| - except: |
| 49 | + |
| 50 | + # if it fails, there is a chance of socket has died |
| 51 | + except Exception as e: |
| 52 | + print('Error broadcasting message: {e}') |
31 | 53 | remove_connection(client_conn)
|
32 | 54 |
|
| 55 | + |
33 | 56 | def remove_connection(conn: socket.socket) -> None:
|
| 57 | + ''' |
| 58 | + Remove specified connection from connections list |
| 59 | + ''' |
| 60 | + |
| 61 | + # Check if connection exists on connections list |
34 | 62 | if conn in connections:
|
| 63 | + # Close socket connection and remove connection from connections list |
35 | 64 | conn.close()
|
36 | 65 | connections.remove(conn)
|
37 | 66 |
|
38 | 67 |
|
39 | 68 | def server() -> None:
|
| 69 | + ''' |
| 70 | + Main process that receive client's connections and start a new thread |
| 71 | + to handle their messages |
| 72 | + ''' |
| 73 | + |
40 | 74 | LISTENING_PORT = 12000
|
41 | 75 |
|
42 | 76 | try:
|
| 77 | + # Create server and specifying that it can only handle 4 connections by time! |
43 | 78 | socket_instance = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
44 |
| - |
45 | 79 | socket_instance.bind(('', LISTENING_PORT))
|
46 | 80 | socket_instance.listen(4)
|
| 81 | + |
| 82 | + print('Server running!') |
47 | 83 |
|
48 | 84 | while True:
|
49 | 85 |
|
| 86 | + # Accept client connection |
50 | 87 | socket_connection, address = socket_instance.accept()
|
51 |
| - |
| 88 | + # Add client connection to connections list |
52 | 89 | connections.append(socket_connection)
|
53 |
| - |
54 |
| - _thread.start_new_thread(handle_user_connection, (socket_connection, address)) |
| 90 | + # Start a new thread to handle client connection and receive it's messages |
| 91 | + # in order to send to others connections |
| 92 | + threading.Thread(target=handle_user_connection, args=[socket_connection, address]).start() |
55 | 93 |
|
56 | 94 | except Exception as e:
|
57 | 95 | print(f'An error has occurred when instancing socket: {e}')
|
58 | 96 | finally:
|
| 97 | + # In case of any problem we clean all connections and close the server connection |
59 | 98 | if len(connections) > 0:
|
60 | 99 | for conn in connections:
|
61 | 100 | remove_connection(conn)
|
|
0 commit comments