python-满足条件(不是计时器)时停止等待input() [英] python - stop waiting for input() when a condition (not timer) is met

查看:645
本文介绍了python-满足条件(不是计时器)时停止等待input()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个新手编程,真的很喜欢使用python进行编程.我目前正在开发一个使用python设置套接字以在两台主机之间建立tcp连接的程序.

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 two hosts.

我的目标是创建一个可以服务于传入连接并启动连接建立的程序.换句话说,一旦程序启动,它将通过服务器的常规套接字设置并开始侦听传入的连接.在程序侦听传入连接的同时,它还为用户提供了通过在控制台中输入IP地址来启动连接的选项.

My goal is to create a program that could serve an incoming connection and also initiate the establishment of a connection. In other words once the program is started it would go through the regular socket setup for a server and start listening for an incoming connection. While the program is listening for an incoming connection, it would also offer the user the option of initiating a connection by inputting an IP address in the console.

目标是...如果用户从不输入IP地址,则程序将继续继续侦听传入的连接. 如果建立了传入连接,程序将从用户输入中退出并通知用户已建立传入连接,然后禁止通过控制台输入建立传出连接的选项.(我知道两者都可以可以通过线程处理,但我希望程序仅处理一个连接,无论是作为服务器还是作为客户端).

The goal is... if the user never input an IP address the program would simply continue to listen for an incoming connection. If an incoming connection was made the program would exit out of the user input and notify the user an incoming connection was made, then disallow the option of establishing an outgoing connection via console input. (I know both could be handled with threading, but I want the program to only handle one connection, whether that be as server or client).

但是,如果用户键入IP地址,则程序将尝试建立与输入IP的连接.如果建立了连接,它将停止侦听传入的连接,而专注于传出的连接.

However, if the user typed an IP address the program would attempt to establish a connection to the inputted IP. If a connection was established it would stop listening for an incoming connection and focus on the outgoing connection.

我在上面强调了我的问题.我需要一种在满足条件时(在建立传入连接时)退出input()提示符的方法.当前,建立连接后,我将打印已建立传入连接!".但是,在此打印后,终端仍会等待用户输入...

I highlighted my problem above. I need a way of exiting out of the input() prompt when a condition is met (when an incoming connection is established). Currently, when a connection is made, I print "Incoming Connection Established!" however, after this is printed the terminal still waits for the user to input...

import socket
import sys
from _thread import *

ipForInitiating = ''

host = ''
port = 5555

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:
    s.bind((host, port))
except socket.error as e:
    print(str(e))

s.listen(2)

def checkForIncoming():
    while ipForInitiating == '':
        conn, addr = s.accept()
        print('################################\nIncoming Connection 
               Established!\n Address = '+addr[0]+':'+str(addr[1]))
        break #Once connection is established break checkForOutgoing() and 
              #CheckForIncoming().  However, continue handleing incoming 
              #connection...

def checkForOutgoing():
    while True:
        if ipForInitiating != '':
            try:
                s.connect((ipForInitiating,port))
            except socket.error as e:
                print(str(e))

            break #Once connection is established break checkForIncoming() 
                  #and CheckForOutgoin.  However, continue handleing 
                  #outgoing connection...

print("Waiting for a connection...")

start_new_thread(checkForIncoming,())
start_new_thread(checkForOutgoing,())

ipForInitiating = input("...Or enter an ip address to initiate the 
connection.\n")

print(ipForInitiating)

推荐答案

在健全的操作系统上,该操作系统还允许

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)

这篇关于python-满足条件(不是计时器)时停止等待input()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆