-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhide_server.py
More file actions
157 lines (126 loc) · 5.23 KB
/
hide_server.py
File metadata and controls
157 lines (126 loc) · 5.23 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
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
import socket
import threading
import time
import json
import random
TIME_DELAY = 0.06
class ClientHandler(threading.Thread):
def __init__(self, client_socket, client_address, server):
super(ClientHandler, self).__init__()
self.client_socket = client_socket
self.client_address = client_address
self.server = server
self.username = 'Guest' + str(random.randint(1000,9999))
self.pixl_model = 200
self.x = 0
self.y = 0
self.z = 0
self.current_map = ''
self.score = 0
def run(self):
print(f"Client {self.client_address} connected.")
while True:
try:
# Receive data from the client
data = self.client_socket.recv(1024)
if not data:
break # Blank = Connection closed
# Split the received data by newline (\n) to handle multiple JSON messages at once
messages = data.decode("utf-8").split("\n")
for message in messages:
if not message:
continue
# Parse the JSON data
try:
data = json.loads(message)
except json.JSONDecodeError as e:
print(f"Error decoding JSON from {self.client_address}: {e}")
continue
# Handle the JSON data here
# print(f"Received from {self.username}: {data}")
if 'username' in data:
self.username = data['username']
if 'x' in data:
self.x = data['x']
if 'y' in data:
self.y = data['y']
if 'z' in data:
self.z = data['z']
if 'current_map' in data:
self.current_map = data['current_map']
except Exception as e:
print(f"Error while receiving data from {self.client_address}: {e}")
break
# Close the client socket when the loop breaks
self.client_socket.close()
print(f"Client {self.client_address} disconnected.")
# Remove the disconnected client from the connections dictionary
del self.server.connections[self.client_address]
class Server(threading.Thread):
def __init__(self, host, port):
super(Server, self).__init__()
self.host = host
self.port = port
self.server_socket = None
self.connections = {}
def run(self):
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.server_socket.bind((self.host, self.port))
self.server_socket.listen(5)
print(f"Server listening on {self.host}:{self.port}")
while True:
try:
client_socket, client_address = self.server_socket.accept()
print(f"New connection from {client_address}")
client_handler = ClientHandler(client_socket, client_address, self)
client_handler.start()
# Store the client handler in the dictionary for future reference
self.connections[client_address] = client_handler
except Exception as e:
print(f"Error accepting connection: {e}")
def stop(self):
self.server_socket.close()
class Game(threading.Thread):
def __init__(self, server):
super(Game, self).__init__()
self.server = server
def run(self):
# Add your main game logic here
while True:
# Access the connections dictionary in the Server class from the Game class
all_connections = self.server.connections
# Game logic to be executed periodically
time.sleep(TIME_DELAY)
if __name__ == "__main__":
# Set your desired host and port for the server
HOST = '0.0.0.0'
PORT = 8080
server = Server(HOST, PORT)
server.start()
game_thread = Game(server) # Server is passed to give Game access to Server data
game_thread.start()
try:
while True:
if server.connections:
all_clients_data = []
for connection in server.connections:
client_info = server.connections[connection]
client_data = {
'username': client_info.username,
'pixl_model': client_info.pixl_model,
'x': client_info.x,
'y': client_info.y,
'z': client_info.z,
'current_map': client_info.current_map,
'score': client_info.score,
}
all_clients_data.append(client_data)
json_data = json.dumps(all_clients_data)
json_data += '\n'
for connection in server.connections:
sock = server.connections[connection].client_socket
sock.send(json_data.encode())
time.sleep(TIME_DELAY)
except KeyboardInterrupt:
server.stop()