-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpythonclient.py
More file actions
281 lines (227 loc) · 7.63 KB
/
pythonclient.py
File metadata and controls
281 lines (227 loc) · 7.63 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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
print("client started")
print("_________________________________________________________________________________")
# client sends self id
# client sends recipient id
# client sends data
from threading import Thread, Lock, Condition
import json
import sys
import socket
import sounddevice as sd
from time import sleep
import pickle
import numpy as np
import random
from Crypto.Cipher import AES
from socket import timeout
# socket connect to the server
SERVER_IP = '34.70.181.155'
# SERVER_IP = '0.0.0.0'
SERVER_PORT = 9001
BUFMAX = 512
running = True
mutex_t = Lock()
item_available = Condition()
# SLEEPTIME = 0.00001
SLEEPTIME = 0.000001
audio_available = Condition()
sdstream = sd.Stream(samplerate=44100, channels=1, dtype='float32')
sdstream.start()
key = b'thisisthepasswordforAESencryptio'
# random.seed(input("ENTER RANDOM SEED :"))
random.seed('changethisrandomseed')
# iv_seed = hash(hash(key))
# random.seed(iv_seed)
iv = ''.join([chr(random.randint(0, 0xFF)) for i in range(16)])
iv = iv.encode()
cipher = AES.new(key, AES.MODE_CBC, iv[:16])
# nonce = cipher.nonce
# ciphertext, tag = cipher.encrypt_and_digest(data)
def get_iv():
return (''.join([chr(random.randint(0, 0xFF)) for i in range(16)])).encode()[:16]
def decrypt(enc_data):
cphr = AES.new(key, AES.MODE_CBC, enc_data[:16])
decoded = cphr.decrypt(enc_data)[16:]
return decoded.rstrip()
def encrypt(data_string):
iv = get_iv()
cphr = AES.new(key, AES.MODE_CBC, iv)
d = iv + data_string
d = (d + (' ' * (len(d) % 16)).encode())
d = d[:(0 - (len(d) % 16))]
return cipher.encrypt(d)
class SharedBuf:
def __init__(self):
self.buffer = np.array([], dtype='float32')
def clearbuf(self):
self.buffer = []
def addbuf(self, arr):
self.buffer = np.append(self.buffer, arr)
def extbuf(self, arr):
self.buffer = np.append(self.buffer, arr)
def getlen(self):
return len(self.buffer)
def getbuf(self):
return self.buffer
def getx(self, x):
data = self.buffer[0:x]
self.buffer = self.buffer[x:]
return data
# record t seconds of audio
def record(t):
global running
if running:
return sdstream.read(t)[0]
def transmit(buf, socket):
global running
# print(f"PICKLED VAL ____ = {pickle.dumps(buf)}")
pickled = pickle.dumps(buf)
# print(f"PICKLED ______ = {pickled}")
encrypted_str = encrypt(pickled)
# decrypted = decrypt(encrypted_str)
# print(f"PICKLED ___ENC = {decrypted}")
try:
socket.send(encrypted_str)
except timeout:
print("SOCKET TIMEOUT")
running = False
except BrokenPipeError:
print("Recipient disconnected")
running = False
def record_transmit_thread(serversocket):
print("***** STARTING RECORD TRANSMIT THREAD *****")
tbuf = SharedBuf()
global running
def recorder_producer(buf):
global running
while running:
sleep(SLEEPTIME)
data = record(32)
with item_available:
item_available.wait_for(lambda: buf.getlen() <= BUFMAX)
buf.extbuf(data)
item_available.notify()
print("RECORDER ENDS HERE")
def transmitter_consumer(buf, serversocket):
global running
while running:
sleep(SLEEPTIME)
with item_available:
item_available.wait_for(lambda: buf.getlen() >= 32)
transmit(buf.getx(32), serversocket)
item_available.notify()
print("TRANSMITTER ENDS HERE")
rec_thread = Thread(target=recorder_producer, args=(tbuf,))
tr_thread = Thread(target=transmitter_consumer, args=(tbuf,serversocket))
rec_thread.start()
tr_thread.start()
rec_thread.join()
tr_thread.join()
return
# use a sound library to play the buffer
def play(buf):
# print("playing_audio")
global running
if running:
sdstream.write(buf)
def receive(socket):
jsn = b''
while running:
while (len(jsn) < 304) and running:
try:
jsn += socket.recv(304)
except timeout:
print("SOCKET TIMEOUT")
yield None
except ConnectionResetError:
print("Recipient disconnected")
yield None
try:
dat = jsn[:304]
# print(len(dat))
# print(len(dat) % 16)
dat = decrypt(dat)
# print(f"DATA RECEIVED = {dat}")
buf = pickle.loads(dat)
except pickle.UnpicklingError:
print(f" @@@@@ UNPICKLE ERROR @@@@@ INPUT______ of len = {sys.getsizeof(jsn)} ::{decrypt(jsn[:304])}")
continue
jsn = jsn[304:]
yield buf
def receive_play_thread(serversocket):
print("***** STARTING RECEIVE PLAY THREAD *****")
rbuf = SharedBuf()
def receiver_producer(buff, serversocket):
global running
rece_generator = receive(serversocket)
while running:
sleep(SLEEPTIME)
# while sys.getsizeof(jsn) < 314:
try:
data = next(rece_generator)
except StopIteration:
break
if data is None:
break
with audio_available:
audio_available.wait_for(lambda: buff.getlen() <= BUFMAX)
buff.extbuf(data)
audio_available.notify()
print("RECEIVER ENDS HERE")
def player_consumer(buff):
while running:
sleep(SLEEPTIME)
with audio_available:
audio_available.wait_for(lambda: buff.getlen() >= 32)
play(buff.getx(buff.getlen()))
audio_available.notify()
print("PLAYER ENDS HERE")
global running
rece_thread = Thread(target=receiver_producer,args=(rbuf, serversocket))
play_thread = Thread(target=player_consumer, args=(rbuf,))
rece_thread.start()
play_thread.start()
# input("press enter to exit")
# running = False
rece_thread.join()
play_thread.join()
return
def main():
serversocket = connect()
global running
t_thread = Thread(target=record_transmit_thread, args=(serversocket,))
p_thread = Thread(target=receive_play_thread, args=(serversocket,))
t_thread.start()
p_thread.start()
input("press enter to exit")
running = False
sdstream.stop()
t_thread.join()
p_thread.join()
serversocket.close()
def connect():
global source_name
global SERVER_IP
global SERVER_PORT
global destination_name
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((SERVER_IP, SERVER_PORT))
source_name = str(input("enter source name :"))
print(f"hello {source_name}")
print(f"message length = {len((source_name + (' '*(512-len(source_name)))).encode())}")
s.send((source_name + (' '*(512-len(source_name)))).encode())
destination_name = str(input("enter destination name :"))
s.send((destination_name + (' '*(512-len(destination_name)))).encode())
sleep(2)
val = s.recv(2)
if val.decode() != 'go':
raise TypeError
# returns socket fd
s.settimeout(5.0)
return s
main()
# 2 separate websocket connections for receiving and sending files
# 2 separate threads to handle transmission and playback of the audio files
# start recording and keep sending data
# disconnect server
print("client terminating")