Last active
November 16, 2015 04:12
-
-
Save jfriedly/d96ed37846c0d32d9f47 to your computer and use it in GitHub Desktop.
Example of how to code a GUI with a socket listener using Python threads
This file contains hidden or 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 socket | |
import threading | |
""" Create a thread listening for client connections and enter the GUI mainloop | |
""" | |
def main(): | |
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
server_socket.bind((socket.gethostname(), 80)) | |
server_socket.listen(5) | |
client_sockets = [] | |
listener_thread = threading.Thread(target=socket_listener) | |
listener_thread.start(server_socket, client_sockets) | |
mainloop(client_sockets) | |
def mainloop(client_sockets): | |
while True: | |
local_user_text = raw_input("> ") # This call blocks | |
# do something in your GUI with whatever the user typed in, i.e.: | |
# for client_socket in client_sockets: | |
# client_socket.send(local_user_text) | |
def socket_listener(server_socket, client_sockets): | |
while True: | |
client_socket, address = server_socket.accept() # This call blocks | |
client_sockets.append(client_socket) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment