-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
176 lines (153 loc) · 6.16 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
import socket
import threading
import time
import traceback
import msgpack
import msgpack_numpy as m
import argparse
import numpy # Make sure NumPy is loaded before it is used in the callback
import wave
from cryptography.fernet import Fernet
import requests
class Server:
#server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
udp_server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#Use 0.0.0.0 after you have port forwarded
#host = "0.0.0.0"
host = "127.0.0.1"
port = 5555
privatekey = b'Hq9vW2opxUZ7ld51Inrz0rvnMhlHtukUnFKrIAyxyOE='
publickey = b'4vF083_jOpvEdqbXqem8GP96wmawb0KKZLz3o43o-KU='
pucryp = Fernet(publickey)
prcryp = Fernet(privatekey)
curclients = []
version = "0.1"
def __init__(self):
server_config = (self.host, self.port)
self.udp_server.bind(server_config)
#self.server.bind(server_config)
#self.server.listen(5)
self.connections = []
self.users = []
self.loggedIN = []
print(f"Server laucnhed {self.host}:{self.port}")
try:
# Use a get request for api.duckduckgo.com
raw = requests.get('https://api.duckduckgo.com/?q=ip&format=json')
# load the request as json, look for Answer.
# split on spaces, find the 5th index ( as it starts at 0 ), which is the IP address
answer = raw.json()["Answer"].split()[4]
# if there are any connection issues, error out
except Exception as e:
print('Error: {0}'.format(e))
# otherwise, return answer
else:
print(answer)
self.acceptConnectionT = threading.Thread(target=self.acceptConnection)
self.acceptConnectionT.daemon = True
self.acceptConnectionT.start()
def int_or_str(self, text):
"""Helper function for argument parsing."""
try:
return int(text)
except ValueError:
return text
def acceptConnection(self):
clients = dict()
timeout = 5
while True:
try:
#This doesnt quiet work yet but still fixing it
d, a = self.udp_server.recvfrom(4096)
clients[a] = time.time()
for addr in clients.copy().keys():
if clients[addr] < (time.time() - timeout):
self.connections.remove(addr)
clients.pop(addr)
print("Removed!")
if a not in self.connections:
if d == b"connection":
self.udp_server.sendto(d,a)
#self.cT = threading.Thread(target=self.handler,args=(d,a))
#self.cT.daemon = True
#self.cT.start()
self.connections.append(a)
print(self.connections)
print("Get connecting from ", a)
else:
for c in self.connections:
if a != c:
self.udp_server.sendto(d, c)
except Exception as ex:
print(traceback.format_exc())
print(self.connections)
if a in self.connections:
self.connections.remove(a)
clients.pop(a)
#print(self.connections)
print(f"{a} has disconnected")
def removeC(self, c):
try:
self.connections.remove(c)
c.close()
except Exception as ex:
try:
c.close()
except Exception as ex:
print(ex)
def handler(self, data ,addr):
try:
#data = c.recv(4096)
#if not data:
# self.removeC(c)
# print(f"{a} has disconnected")
# break
#print(data)
d, a = self.udp_server.recvfrom(4096)
if a == addr:
for c in self.connections:
if a != c:
self.udp_server.sendto(d, c)
#data = msgpack.unpackb(data, object_hook=m.decode)
#self.output_stream.write(data)
#data = self.pucryp.decrypt(data).decode()
#data = data.split()
#for connection in self.connections:
# if connection != c:
# connection.send(data)
''' if data[0] == "Connection":
print("Connection secured")
if data[1] == "Audio":
print(data)
c.send(self.pucryp.encrypt(bytes("Audio recieved", 'utf-8'))) '''
except Exception as ex:
if a == addr:
print(ex)
self.connections.remove(addr)
print(self.connections)
print(f"{addr} has disconnected")
def removeHandler(self,c,a,uuid):
while True:
counter = 0
time.sleep(5)
for i in self.loggedIN:
if i[1] == uuid:
for x in self.users:
if self.users[x]["uuid"] == str(uuid):
counter += 1
if counter == 0:
c.send(self.pucryp.encrypt(bytes("invalid username or password", 'utf-8')))
self.removeC(c)
self.loggedIN.remove((a,uuid))
break
def chat(self):
while True:
server_message = input()
server_message = server_message.split()
# server_message = "\nserver:{}\n".format(server_message)
# server_message = self.pucryp.encrypt(bytes(server_message, 'utf-8'))
# for c in self.connections:
# c.send(self.pucryp.encrypt(bytes(server_message, 'utf-8')))
if __name__ == '__main__':
Server_m = Server()
Server_m.chat()