简体   繁体   English

有什么方法可以检查Python Socket中是否有传入消息

[英]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.

相关问题 有没有办法检查套接字的数据缓冲区在Python中是否为空? - Is there a way to check whether the data buffer for a socket is empty or not in python? Python套接字绑定0.0.0.0,检查传入消息 - Python socket bind 0.0.0.0, inspect incoming message 如何从python raw socket中的传入数据包中获取消息 - How to get message from incoming packets in python raw socket Python 2.7.10:除了使用len()以外,还有其他方法可以检查输入是否为空 - Python 2.7.10 :Is there any other way to check whether an input is empty other than using len() UDP 套接字没有收到任何带有 python 的消息 - UDP Socket is not receiving any message with python 检查是否有任何套接字连接正在等待(python) - Check if any socket connections are waiting (python) 有什么方法可以检查列表是否在 np.array 中? - Is there any way to check whether a list is in np.array? 有没有一种方法可以使ZeroMQ在所有传入/传出消息模式的单个套接字上工作? - Is there a way to make ZeroMQ work on one socket for all incoming/outgoing message patterns? 套接字断开连接后,有什么方法可以在Python中使用getpeername()? - Is there any way to getpeername() in Python after the socket disconnects? 检查 python 中是否有任何属性的任何替代方法? - Any alternative way to check if there is any attribute in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM