首页 > 解决方案 > 如何在python中设置超时并打印时间倒计时

问题描述

我创建了一个 TCP 服务器并将超时设置为 30 秒,但我希望超时倒计时实时显示在屏幕上,并Client not connected在 30 秒后打印。

预期输出:

import socket 
#import datetime
import time

def countdown(t):
    while t:
        mins, secs = divmod(t, 60)
        timer = '{:02d}:{:02d}'.format(mins, secs)
        print(timer, end="\r")
        time.sleep(1)
        t -= 1
t = 30
#countdown(t)

def SocketServer():
    host = input ("Enter the server IP addresss:" )
    port = 8888
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    try:
        s.bind((host, port))
        s.listen(2)
        s.settimeout(t)

        print(""" ***********************************************************
  This Server will timeout if no client connect in 30 seconds
 ************************************************************""")
        countdown(t)

        conn, addr = s.accept()     
        print(addr, "connectiom is establish")
        conn.send("Hello Client!".encode())
        conn.close()

    except socket.timeout:    
        print("client not connected!")
        s.close()

SocketServer()

标签: python

解决方案


我希望这能帮到您!我将发布客户端与此服务器连接的代码!我写了几行来指导你!

import socket
import threading
import time
class SocketServer():
    def __init__(self):
        self.t=30
        self.adr=""
        print(""" ***********************************************************
         This Server will timeout if no client connect in 30 seconds
        ************************************************************""")
        #let's create a new thread for out server
        # in the main thread, we will print and count seconds....
        self.thread=threading.Thread(target=self.thread)
        self.thread.daemon=True
        self.thread.start()
        self.counter()

    def thread(self):
        HOST = '127.0.0.1'  # The server's hostname or IP address
        PORT = 8888  # The port used by the server
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.bind((HOST, PORT))
            s.listen()
            conn, addr = s.accept()
            with conn:
                print('Connected by', addr)
                #we want to know if someone is connected
                #by set self.adr with something that has len>0 we will informe the main thread that it needs to stop
                self.adr="Connected"
                conn.send("Hello Client!".encode())
                s.close() #if you want to close, or leave it to further connections
    def counter(self):
        for x in range(self.t + 1):
            time.sleep(1)#sleep function
            if (len(self.adr)!=0): #every time we chech if sel.adr is different from 0
                print("Connection is established")
                print("Connected after 00:{:02d}".format(x))
                break #stop
            else:
                print ('00:{:02d}'.format(x))

#host = raw_input("Enter the server IP addresss:")
SocketServer()

客户端代码!

import socket

HOST = '127.0.0.1'  # The server's hostname or IP address
PORT = 8888        # The port used by the server

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((HOST, PORT))
    s.sendall(b'Hello, world')
    data = s.recv(1024)

print('Received', repr(data))

输出:

 ***********************************************************
         This Server will timeout if no client connect in 30 seconds
        ************************************************************
00:00
00:01
00:02
00:03
Connected by ('127.0.0.1', 27191)
Connection is established
Connected after 00:04

客户端输出:

Received b'Hello Client!'

推荐阅读