SHARE
TWEET

Python TCP Asyncio and Tkinter

rharder Feb 3rd, 2017 (edited) 163 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/env python3
  2. """
  3. An example of how to use asyncio event loops and tkinter event loops in the same program.
  4.  
  5. Discussed here: http://blog.iharder.net/2017/02/03/python-asyncio-and-tkinter-together/
  6. UDP Version: http://pastebin.com/PeHHRR4E
  7. TCP Version: http://pastebin.com/ZGeDULR9
  8. """
  9. import asyncio
  10. import threading
  11. import tkinter as tk
  12. from functools import partial
  13.  
  14. __author__ = "Robert Harder"
  15.  
  16.  
  17. def main():
  18.     tk_root = tk.Tk()
  19.     Main(tk_root)
  20.     tk_root.mainloop()
  21.  
  22.  
  23. class Main:
  24.     def __init__(self, tk_root):
  25.         # Tk setup
  26.         self.lbl_var = tk.StringVar()
  27.         tk_root.title("Tk Asyncio Demo")
  28.         tk.Label(tk_root, text="Incoming Message, TCP Port 9999:").pack()
  29.         tk.Label(tk_root, textvariable=self.lbl_var).pack()
  30.  
  31.         # Prepare coroutine to connect server
  32.         self.transport = None  # type: asyncio.WriteTransport
  33.  
  34.         @asyncio.coroutine
  35.         def _connect():
  36.             loop = asyncio.get_event_loop()  # Pulls the new event loop because that is who launched this coroutine
  37.             yield from loop.create_server(lambda: self, "127.0.0.1", 9999)
  38.  
  39.         # Thread that will handle io loop
  40.         def _run(loop):
  41.             asyncio.set_event_loop(loop)
  42.             loop.run_forever()
  43.  
  44.         ioloop = asyncio.new_event_loop()
  45.         asyncio.run_coroutine_threadsafe(_connect(), loop=ioloop)  # Schedules connection
  46.         t = threading.Thread(target=partial(_run, ioloop))
  47.         t.daemon = True  # won't hang app when it closes
  48.         t.start()  # Server will connect now
  49.  
  50.     def connection_made(self, transport):
  51.         print("connection_made")
  52.         self.transport = transport
  53.  
  54.     def connection_lost(self, exc):
  55.         print("connection_lost", exc)
  56.  
  57.     def eof_received(self):
  58.         print("eof_received")
  59.  
  60.     def data_received(self, data):
  61.         data_string = data.decode()
  62.         print("data_received", data_string.strip())
  63.         self.transport.write("RECVD: {}\n".format(data_string).encode())
  64.         self.lbl_var.set(data_string.strip())
  65.  
  66.  
  67. if __name__ == "__main__":
  68.     main()
RAW Paste Data
Top