Example of a synergistic program (multitask)

Source: Internet
Author: User

#!/usr/bin/python
#coding: Utf-8

From __future__ import with_statement
From Contextlib import closing
Import socket
Import multitask

def client_handler (sock):
With closing (sock):
While True:
Data= (Yield multitask.recv (sock,1024))
If not data:
Break
Yield Multitask.send (sock,data)

def echo_server (Hostname,port):
Addrinfo=socket.getaddrinfo (Hostname,port,socket.af_unspec,socket. SOCK_STREAM)
(FAMILY,SOCKTYPE,PROTO,CANONNAME,SOCKADDR) =addrinfo[0]
With closing (Socket.socket (Family,socktype,proto)) as sock:
Sock.setsockopt (socket. Sol_socket,socket. so_reuseaddr,1)
Sock.bind (SOCKADDR)
Sock.listen (5)
While True:
Multitask.add (Client_handler (yield multitask.accept (sock)) [0])

If __name__== ' __main__ ':
Import Sys
Hostname=none
port=1111
If Len (SYS.ARGV) >1:
HOSTNAME=SYS.ARGV[1]
If Len (SYS.ARGV) >2:
Port=int (Sys.argv[2])
Multitask.add (Echo_server (Hostname,port))
Try
Multitask.run ()
Except Keyboardinterrupt:
Pass

Copy of the book, after the code again to explain, at present still do not understand

Example of a synergistic program (multitask)

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.