1import select
2import socket
3
4ip = '127.0.0.1'
5port = 80
6
7conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
8conn.connect((ip, port))
9
10while True:
11 try:
12 ready_to_read, ready_to_write, in_error = \
13 select.select([conn,], [conn,], [], 5)
14 except select.error:
15 conn.shutdown(2) # 0 = done receiving, 1 = done sending, 2 = both
16 conn.close()
17 # connection error event here, maybe reconnect
18 print('connection error')
19 break
20 if len(ready_to_read) > 0:
21 recv = conn.recv(2048)
22 # do stuff with received data
23 print(f'received: {recv}')
24 if len(ready_to_write) > 0:
25 # connection established, send some stuff
26 conn.send('some stuff')