Created
March 26, 2019 23:25
-
-
Save 0xpizza/bb3eb3f9e01b482c32d1e27c3e354ea3 to your computer and use it in GitHub Desktop.
async chat
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import queue | |
import asyncio | |
import threading | |
from tkinter import * | |
from tkinter.ttk import * | |
async def receiver(r): | |
while True: | |
Qin.put_nowait(await r.read(100)) | |
async def sender(w): | |
while True: | |
w.write(await Qout.get()) | |
await w.drain() | |
Qout.task_done() | |
async def main(): | |
r,w = await asyncio.open_connection('localhost', 4321) | |
a = asyncio.create_task(sender(w)) | |
b = asyncio.create_task(receiver(r)) | |
await asyncio.gather(a,b) | |
def populate_text(): | |
while True: | |
text.insert(END, Qin.get().decode()) | |
def submit(): | |
msg = entry.get().encode() | |
entry.delete(0,END) | |
loop.call_soon_threadsafe(lambda: Qout.put_nowait(msg)) | |
# Qout.put_nowait(msg) | |
loop = asyncio.get_event_loop() | |
Qin = queue.Queue() | |
Qout = asyncio.Queue(loop=loop) | |
n = threading.Thread(target=loop.run_until_complete, args=(main(),), daemon=True) | |
p = threading.Thread(target=populate_text, daemon=True) | |
tk = Tk() | |
text = Text(tk) | |
text.pack() | |
entry = Entry(tk) | |
entry.pack(fill=X) | |
entry.bind('<Return>', lambda cb: submit()) | |
tk.after(1, n.start) | |
tk.after(1, p.start) | |
tk.mainloop() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment