-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
87 lines (62 loc) · 2.42 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
# Import required modules
import socket
import threading
# HOST = '127.0.0.1'
HOST = '192.168.1.35' #Use same IPV4 adress
PORT = 8080 # You can use any port between 0 to 65535
LISTENER_LIMIT = 10
active_clients = [] # List of all currently connected users
# Function to listen for upcoming messages from a client
def listen_for_messages(client, username):
while 1:
message = client.recv(2048).decode('utf-8')
if message != '':
final_msg = username + '~' + message
send_messages_to_all(final_msg)
else:
print(f"The message send from client {username} is empty")
# Function to send message to a single client
def send_message_to_client(client, message):
client.sendall(message.encode())
# Function to send any new message to all the clients that
# are currently connected to this server
def send_messages_to_all(message):
for user in active_clients:
send_message_to_client(user[1], message)
# Function to handle client
def client_handler(client):
# Server will listen for client message that will
# Contain the username
while 1:
username = client.recv(2048).decode('utf-8')
if username != '':
active_clients.append((username, client))
prompt_message = "SERVER~" + f"{username} added to the chat"
send_messages_to_all(prompt_message)
break
else:
print("Client username is empty")
threading.Thread(target=listen_for_messages, args=(client, username, )).start()
# Main function
def main():
# Creating the socket class object
# AF_INET: we are going to use IPv4 addresses
# SOCK_STREAM: we are using TCP packets for communication
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Creating a try catch block
try:
# Provide the server with an address in the form of
# host IP and port
server.bind((HOST, PORT))
print(f"Running the server on {HOST} {PORT}")
except:
print(f"Unable to bind to host {HOST} and port {PORT}")
# Set server limit
server.listen(LISTENER_LIMIT)
# This while loop will keep listening to client connections
while 1:
client, address = server.accept()
print(f"Successfully connected to client {address[0]} {address[1]}")
threading.Thread(target=client_handler, args=(client, )).start()
if __name__ == '__main__':
main()