first code
This commit is contained in:
parent
00b0b636c0
commit
640dbc0081
54
client.py
54
client.py
@ -0,0 +1,54 @@
|
||||
import socket
|
||||
import json
|
||||
import time
|
||||
import datetime
|
||||
import threading
|
||||
import select
|
||||
|
||||
HOST = "127.0.0.1"
|
||||
PORT = 65432
|
||||
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):
|
||||
while run:
|
||||
ready_to_read, _, _ = select.select([s], [], [], 1.0)
|
||||
if ready_to_read:
|
||||
data = s.recv(1024)
|
||||
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"])
|
||||
# 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")
|
||||
|
||||
else:
|
||||
payload = make_payload(name, msg)
|
||||
s.sendall(payload)
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
name = input("Enter name: ")
|
||||
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||
s.connect((HOST, PORT))
|
||||
threading.Thread(target=event_handel, args=(name, s,)).start()
|
||||
read_msg(s)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
print("Exit with CTRL+C")
|
||||
finally:
|
||||
pass
|
||||
Loading…
x
Reference in New Issue
Block a user