-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstart.py
More file actions
68 lines (55 loc) · 1.92 KB
/
start.py
File metadata and controls
68 lines (55 loc) · 1.92 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
import socket
import threading
from cryptography.fernet import Fernet
import json
import sys, os
import threading
key = "ab-YPb_Hzm0_eypRz0bG8bLeReGB1guJvQnYiuCxJoE="
cipher = Fernet(key)
print(f"Key: {key}")
def clear_console():
os.system('cls' if os.name == 'nt' else 'clear')
chat_history = []
def send_message(sock):
while True:
msg = input()
chat_history.append(f"{username}: {msg}")
clear_console()
for line in chat_history:
print(line)
data_obj = {
"username": username,
"message": msg
}
encrypted_msg = cipher.encrypt(json.dumps(data_obj).encode())
sock.sendall(encrypted_msg)
def receive_message(sock):
while True:
data = sock.recv(1024)
decrypted_msg = cipher.decrypt(data).decode()
msg_obj = json.loads(decrypted_msg)
chat_history.append(f"{msg_obj['username']}: {msg_obj['message']}")
clear_console()
for line in chat_history:
print(line)
def main():
global username
username = input("What is your nickname: ")
choice = input("(l)isten or (c)onnect? ")
if choice == 'l':
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(('0.0.0.0', 12345))
s.listen()
conn, addr = s.accept()
with conn:
print(f"Connected by: {addr}")
threading.Thread(target=receive_message, args=(conn,), daemon=True).start()
send_message(conn)
elif choice == 'c':
host = input("What is the IP of the host? ")
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((host, 12345))
threading.Thread(target=receive_message, args=(s,), daemon=True).start()
send_message(s)
if __name__ == "__main__":
main()