Created
March 4, 2017 11:42
-
-
Save xiazhibin/a1b8fcde3d84c610277914cf6849a09c to your computer and use it in GitHub Desktop.
python select
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
| from select import select | |
| import socket | |
| import Queue | |
| server = socket.socket() | |
| server.bind(('127.0.0.1', 8888)) | |
| server.listen(5) | |
| server.setblocking(0) | |
| input_list = [server, ] | |
| output_list = [] | |
| num = 0 | |
| while True: | |
| print("waiting for next event...") | |
| readable, writeable, std_err = select(input_list, output_list, input_list) | |
| for sock in readable: | |
| if sock == server: | |
| conn, addr = server.accept() | |
| conn.setblocking(0) | |
| input_list.append(conn) | |
| else: | |
| try: | |
| msg = sock.recv(1) | |
| print 'get msg:', msg.decode() | |
| if msg: | |
| if sock not in output_list: | |
| output_list.append(sock) | |
| else: | |
| input_list.remove(sock) | |
| sock.close() | |
| except socket.error, e: | |
| if sock in output_list: | |
| output_list.remove(sock) | |
| input_list.remove(sock) | |
| for sock in writeable: | |
| sock.send('get') | |
| output_list.remove(sock) | |
| server.close |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment