Python implements asynchronous callback mechanism code sharing

Source: Internet
Author: User
1 Copy the following code to a file named asyncore.py

The code is as follows:


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

2 Writing Your own code

1> Import Asyncore

2> defines a callback function Callback,callback requires a parameter to return data on behalf of the request

3> Directly calls Asyncore.ds_asyncore ((' 127.0.0.1 ', 33333), callback,timeout=5), where the first parameter is a (ip,port) tuple, the second is a callback function, and the third is the time-out.

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)

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.