我有以下代碼:
import click
import time
import socket
@click.group(chain=True)
def cli():
pass
j = 0
@cli.command()
def main():
global j
while j == 0:
print("Hi")
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: #This is our server
s.bind((socket.gethostname(), 1234))
s.listen(5)
clientsocket, adress = s.accept()
print(f"Connection from {adress} has been estanblishded !")
msg = clientsocket.recv(1024)
decodedmsg = msg.decode()
print(decodedmsg)
j = int(decodedmsg)
print(str(j))
time.sleep(1)
@cli.command()
def toggle():
clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientSocket.connect((socket.gethostname(), 1234))
data = "1" #what we want to send
clientSocket.send(data.encode()) #telling the client to send the information to the server
if __name__ == "__main__":
cli()
到目前為止,如果我運行該檔案,我會得到 Hi,并且程式會等待連接。
我希望在 j=0 時讓我的程式每秒列印一次 Hi。這個想法是程式正在列印 Hi 直到python3 pathto/program.py toggle被執行。有人知道我如何調整代碼嗎?
uj5u.com熱心網友回復:
s.accept()阻塞直到有連接。為了防止它阻塞,使用select.select()超時來查詢服務器套接字是否準備好連接。如果超時,繼續列印“Hi”。
import click
import socket
import select
@click.group(chain=True)
def cli():
pass
@cli.command()
def main():
counter = 0
# Set up the server
with socket.socket() as s:
s.bind(('', 1234))
s.listen()
with s: # ensure it will be closed when block exits
while counter == 0:
print('Hi')
# readers will be empty on timeout or contain [s]
# if a connection is ready
readers, _, _ = select.select([s], [], [], 1.0)
if s in readers:
clientsocket, address = s.accept()
with clientsocket: # ensure socket will close
print(f"Connection from {address} has been established!")
counter = int(clientsocket.recv(1024))
print(counter)
@cli.command()
def toggle():
clientSocket = socket.socket()
clientSocket.connect((socket.gethostname(), 1234))
with clientSocket:
data = "1" #what we want to send
clientSocket.send(data.encode()) #telling the client to send the information to the server
if __name__ == "__main__":
cli()
test main在一個命令視窗中運行并test toggle在另一個命令視窗中運行幾秒鐘后的輸出:
Hi
Hi
Hi
Hi
Connection from ('192.168.1.3', 7530) has been established!
1
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/512346.html
標籤:Python插座
上一篇:UDP客戶端未收到回應
