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