Python Forum

Full Version: socket without blocking loop and automatically retrieve data from the port
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have a program in a loop.
how to add data transmission via socket in a loop without blocking the loop itself.
and automatically retrieve data from the port if there is data transmission from the client (maybe an event-driven concept)

code :
bind_port = 1234
# create as a server

def myloop ():
    global dataRX
    loopx=1
    while loopx < 10000:
          dataTX = process (DataRX)
          sock.send(dataTX) #send dataTX via port 
          loopx = loopx + 1   


def receive ():
#automatically retrieve data from client
       DataRX = sock.recv() # get data from client

process (param):
       ... code process ...
Thank You
Sockets have a setblocking(bool) method that can be used to prevent a loop from blocking. An example of event driven program for a socket server is shown in the documentation of the selectors module. You could probably use this code.
I use this program code.
the disadvantage of this code is program speed decreases and loop into one part with the socket program.

Is there a solution so that the loop is separate from the socket program like other programming events such as "OnReceive", "OnConnect"

code :
    service = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    service.bind(("", PORT))
    service.listen(1)
    global datarx
    print ("listening on port", PORT)
    datarx=""
    process = 1
    while 1:
        is_readable = [service]
        is_writable = []
        is_error = []
        
        r, w, e = select.select(is_readable, is_writable, is_error, 1.0)
        if r :
            channel, addr = service.accept()      
            request = channel.recv(1024)    
            datarx=request.decode()
            channel.send(request)
            print('request ', request)
            channel.close() # disconnect
            
        else:
            # my program loop
            if continue == 1 :
               --- process 
                 if datarx = '1' :
                    -- process 1
                 else :
                     --- process 2 
                 if process == complete :
                       continue = 0 
    
A solution that I have used in the pass is to create a socketserver.ThreadingTCPServer instance and launch a thread that runs the server's serve_forever() method. One needs to create a subclass of socketserver.StreamRequestHandler with a handle() method that does something useful.Once the server is launched, the main thread can do anything it wants and the socketserver will handle connections and requests in other threads as they arrive.