SoFunction
Updated on 2024-11-15

Cross-platform python asynchronous callback mechanism implementation and usage

1 Copy the following code into a file named

Copy Code The code is as follows.

import socket
import select
import sys

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

2 Write your own code

1> import asyncore

2> define the callback function callback, callback needs a parameter, on behalf of the request to return data

3> Call asyncore.ds_asyncore(('127.0.0.1', 33333),callback,timeout=5) directly, where the first argument is an (ip,port) tuple, the second is the callback function, and the third is the timeout.

Copy Code The code is as follows.

import asyncore

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

Note: This code can be run on windows and linux.