Yusuf Selim KARATAS
Yusuf Selim KARATAS

Reputation: 115

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. I need it to print if there is an incoming message. If there is not an incoming message, just will write 'NO DATA'

I have tried to check with an if condition but it did not work:

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

Upvotes: 1

Views: 3445

Answers (1)

sanyassh
sanyassh

Reputation: 8540

Try using 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

Upvotes: 1

Related Questions