[英]Is there any way to check whether there is an incoming message in Python Socket
I am using a socket in Python and trying to find out how to check whether there is an incoming message in the code.我在 Python 中使用套接字并试图找出如何检查代码中是否有传入消息。 I need it to print if there is an incoming message.
如果有传入消息,我需要它来打印。 If there is not an incoming message, just will write 'NO DATA'
如果没有传入消息,则只写“NO DATA”
I have tried to check with an if condition but it did not work:我试图检查 if 条件,但没有奏效:
import socket
import time
#AG AYARLARI
HOST = ''
PORT = 16000
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((HOST,PORT))
#AGI BASLATMA
s.listen(1)
conn, addr = s.accept()
i=0
print('I:::',i)
print('Connected by', addr)
while True:
data=conn.recv(1024)
if data:
print(data)
else:
print (str.encode('No data'))
break
If there is a message take: "Message"如果有消息采取:“消息”
If not: "No Data"如果不是:“无数据”
Try using select
:尝试使用
select
:
import select
timeout = 10 # in seconds
ready_sockets, _, _ = select.select(
[conn], [], [], timeout
)
if ready_sockets:
data = conn.recv(1024)
print(data)
else:
print('No data')
Read more about it here: https://docs.python.org/3.7/library/select.html在此处阅读更多相关信息: https : //docs.python.org/3.7/library/select.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.