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.