Python implements asynchronous callback mechanism code sharing

Source: Internet
Author: User

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

Copy codeThe 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. Write your own code

1> Import asyncore

2> define the callback function callback. callback requires a parameter that represents the data returned by the request.

3> directly call asyncore. ds_asyncore ('2017. 0.0.1 ', 33333), callback, timeout = 5). The first parameter is an (ip, port) tuple, the second parameter is the callback function, and the third parameter is the timeout time.

Copy codeThe Code is as follows:
Import asyncore

If _ name __= = "_ main __":
Def callback (respose_data ):
Print respose_data
Asyncore. ds_asyncore ('127. 0.0.1 ', 127), 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.