Python high concurrent Asynchronous Server Core Library Forkcore use method _python

Source: Internet
Author: User

1 Copy the following code to a file and name it forkcore.py

Copy Code code as follows:

Import OS
Import threading
Import Select
Import socket

Class Ds_forkcore (object):

#async IO (Epoll)
def ds_epoll (self):
Epoll=select.epoll ()
Epoll.register (Self.s.fileno (), select. Epollin|select. Epollet)
While 1:
Epoll_list=epoll.poll ()
For fd,_events in Epoll_list:
If Fd==self.s.fileno ():
Conn,addr=self.s.accept ()
Print "Current process ' s-pid is" +str (Os.getpid ())
Self.worker (CONN,ADDR)

#multi_thread
def ds_thread (self,thread_num=100):
For _ in range (0,thread_num):
T=threading. Thread (Target=self.ds_epoll)
T.setdaemon (1)
T.start ()
T.join ()

#multi_process
def ds_process (self,child_process_num=8):
Pid=os.getpid ()
Print "Main process start, PID is" +STR (PID)
For _ in range (0,child_process_num):
If Pid==os.getpid ():
If Os.fork ():
Pass
Else
Print "Worker process start, PID is" +str (Os.getpid ())
Self.ds_thread ()

#init function
def __init__ (self,worker,port=3333):
S=socket.socket (Socket.af_inet,socket. SOCK_STREAM)
S.setsockopt (socket. Sol_socket,socket. so_reuseaddr,1)
S.bind (("", Port)
S.listen (50000)
Self.s=s
Self.worker=worker
Self.ds_process ()

2 Write your own code

1> Import Forkcore Library.

2> defines the worker function, the worker function requires two parameters, and the conn that represents the client connection is a tuple of (ip,port).

3> directly using Forkcore.ds_forecore (worker,port=5555), port is used to specify the listening port.

Copy Code code as follows:

Import Forkcore

If __name__== "__main__":
def worker (CONN,ADDR):
Print "Message from (" +str (addr[0]) + ": +str (addr[1) +"): "+CONN.RECV (1024) [0:-1]

Forkcore.ds_forkcore (worker,port=5555)

Note: Linux requires more than 2.6 of the kernel

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.