69 lines
1.8 KiB
Python
69 lines
1.8 KiB
Python
import socket
|
|
import json
|
|
import time
|
|
import datetime
|
|
import threading
|
|
import select
|
|
|
|
run = True
|
|
|
|
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"])
|
|
else:
|
|
print("Server disconnected")
|
|
run = False
|
|
# print(f"Received {data!r}")
|
|
|
|
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()
|
|
read_msg(s)
|
|
except ConnectionRefusedError:
|
|
print("Could not connect to the server!")
|
|
finally:
|
|
s.close()
|
|
|
|
|
|
except KeyboardInterrupt:
|
|
print("Exit with CTRL+C")
|