How to Use forkcore, the core library of python high-concurrency Asynchronous Server

Source: Internet
Author: User

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

Copy codeThe Code is 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 the forkcore library.

2> define the worker function. The worker function requires two parameters. conn indicates the socket connected to the client. addr is the (ip, port) tuples.

3> Use forkcore. ds_forecore (worker, port = 5555) to specify the listening port.

Copy codeThe Code is 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 2.6 and later kernels are required.

Related Article

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.