Python implements asynchronous callback mechanism code sharing

  • 2020-04-02 13:19:46
  • OfStack

1 copy the following code to a file named asyncore.py


import socket
import select
import sys
def ds_asyncore(addr,callback,timeout=5):
    s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    s.connect(addr)
    r,w,e = select.select([s],[],[],timeout)
    if r:
        respose_data=s.recv(1024)
        callback(respose_data)
        s.close()
        return 0
    else:
        s.close()
        return 1

Write your own code

1 > Import the asyncore

2 > Define the callback function callback, which takes an argument to return data on behalf of the request

3 > Directly call asyncore.ds_asyncore(('127.0.0.1', 33333),callback,timeout=5), where the first parameter is a (IP,port) tuples, the second is a callback function, and the third is a timeout.


import asyncore
if __name__=="__main__":
    def callback(respose_data):
        print respose_data
    asyncore.ds_asyncore(('127.0.0.1', 33333),callback,timeout=5)


Related articles: