non blicking input
This commit is contained in:
parent
9d8eb07570
commit
db20635094
56
client.py
56
client.py
@ -1,11 +1,15 @@
|
||||
import socket
|
||||
import json
|
||||
import time
|
||||
import datetime
|
||||
import threading
|
||||
import datetime
|
||||
import select
|
||||
import sys
|
||||
import termios
|
||||
import tty
|
||||
|
||||
run = True
|
||||
new_msg = []
|
||||
|
||||
def make_payload(name, msg):
|
||||
payload = {
|
||||
@ -23,13 +27,56 @@ def read_msg(s):
|
||||
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"])
|
||||
# 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:
|
||||
@ -56,7 +103,8 @@ if __name__ == "__main__":
|
||||
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=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!")
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user