Skip to content Skip to sidebar Skip to footer

Python - Stop Waiting For Input() When A Condition (not Timer) Is Met

I am a novice programming that really enjoys programming with python. I am currently working on a program that uses python to set up sockets to establish a tcp connection between

Solution 1:

On a sane operating system, which allows also non-socket descriptors in a select.select call, we can check the readable descriptors returned therefrom to decide whether to accept an incoming or to make an outgoing connection.

import select
import socket
import sys

host = ''
port = 5555

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(0)

print("Waiting for a connection...")
print("...Or enter an IP address to initiate the connection.")

if s in select.select([s, sys.stdin], [], [])[0]:   # only interest in readable
    conn, addr = s.accept()
    print('################################\nIncoming Connection Established!\n'
          'Address = '+addr[0]+':'+str(addr[1]))
else:
    ipForInitiating = input()
    conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    conn.connect((ipForInitiating, port))
    print(ipForInitiating)

Post a Comment for "Python - Stop Waiting For Input() When A Condition (not Timer) Is Met"