sockets_python/client.py
2025-11-24 22:03:59 +01:00

117 lines
3.5 KiB
Python

import socket
import json
import time
import threading
import datetime
import select
import sys
import termios
import tty
run = True
new_msg = []
def make_payload(name, msg):
payload = {
"name": name,
"msg": msg,
"time": time.time()
}
return json.dumps(payload).encode("utf-8")
def read_msg(s):
global run
while run:
ready_to_read, _, _ = select.select([s], [], [], 1.0)
if ready_to_read:
data = s.recv(1024)
if data:
msg = json.loads(data.decode("utf-8"))
# print(f"{msg["name"]} {datetime.datetime.fromtimestamp(float(msg["time"])).strftime("%d-%m-%Y %H:%M")}")
# print(msg["msg"])
new_msg.append(msg)
else:
print("Server disconnected")
run = False
# print(f"Received {data!r}")
def input_handel(name, s):
global run
msg_buffer = ""
old_settings = termios.tcgetattr(sys.stdin)
try:
tty.setraw(sys.stdin.fileno())
print("\r> " + msg_buffer, end="")
while run:
if select.select([sys.stdin], [], [], 0)[0]:
ch = sys.stdin.read(1)
if ord(ch) == 127:
if len(msg_buffer) > 0:
msg_buffer = msg_buffer[:-1]
print("\r> " + msg_buffer + " ", end="")
elif ord(ch) == 13:
if msg_buffer in ["", " "]:
run = False
print("\r\nClosing socket and exit")
elif run:
payload = make_payload(name, msg_buffer)
s.sendall(payload)
msg_buffer = ""
print("\r\n> ", end="")
else:
msg_buffer += ch
print("\r> " + msg_buffer, end="")
else:
time.sleep(0.1)
if len(new_msg) > 0:
msg = new_msg.pop()
print(f"\r{msg["name"]} {datetime.datetime.fromtimestamp(float(msg["time"])).strftime("%d-%m-%Y %H:%M")}")
print("\r" + msg["msg"])
print()
print("\r> " + msg_buffer, end="")
finally:
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
def event_handel(name, s):
global run
while run:
msg = input("> ")
if msg in ["", " "]:
run = False
print("Closing socket and exit")
elif run:
payload = make_payload(name, msg)
s.sendall(payload)
if __name__ == "__main__":
try:
HOST = input("Enter ip: (default 127.0.0.1) ")
if HOST == "":
HOST = "127.0.0.1"
PORT_str = input("Enter port: (default 65432) ")
if PORT_str == "":
PORT = 65432
else:
PORT = int(PORT_str)
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
name = input("Enter name: ")
# threading.Thread(target=event_handel, args=(name, s,)).start()
threading.Thread(target=input_handel, args=(name, s,)).start()
read_msg(s)
except ConnectionRefusedError:
print("Could not connect to the server!")
finally:
s.close()
except KeyboardInterrupt:
print("Exit with CTRL+C")