python - 如何在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()
解决方案
我希望这能帮到您!我将发布客户端与此服务器连接的代码!我写了几行来指导你!
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!'
推荐阅读
- angular - 如何将数据(Json 对象)从 Angular 2 发布到 Web api?
- typescript - 打字稿类对象存储到firebase db
- android - Android - LocationManager requestLocationUpdates 回调在 Lollipop 上不起作用
- excel - Excel VBA从具有文件路径的单元格中附加多个文件
- ruby-on-rails - 如何让我的数据库查询更高效?
- javascript - 如何在 javascript 中将相同的键值对(以不同的顺序)表示为 Map 的相同键?
- java - 带底栏的浮动操作按钮
- c# - 从 url 获取 json 数据并输出为 csv 文件
- java - 我想用 Java 打印这个模式
- web - 网站无法在移动设备上打开