It's nothing today. Practice Python's epoll and start by writing a client:
#!/usr/pythonImportSOCKET,SYS,SELECTC=Socket.socket (Socket.af_inet,socket. SOCK_STREAM) Host='127.0.0.1'Port=57777C.connect ((host,port)) epoll_fd=Select.epoll () Epoll_fd.register (C.fileno (), select. Epollin) Epoll_fd.register (Sys.stdin.fileno (), select. Epollin) Str="" whiletrue:e_list=Epoll_fd.poll () forFd,eventsinche_list:ifFD = = C.fileno () andevents&Select. Epollin:buf= C.RECV (1024) if notLen (buf): Break Print "ser:", bufifFD = = C.fileno () andEvents &Select. Epollout:#print ' Send msg to ser. 'c.send (str) epoll_fd.modify (C.fileno (), select. Epollin)ifFD = = Sys.stdin.fileno () andEvents &Select. Epollin: str ="SSF"epoll_fd.modify (C.fileno (), select. Epollout) C.close ()
Discovering that the server is always in the loop to collect information, is very confusing. Later modified the str= "SSF", modified to Raw_input, found that the normal operation of the program, suddenly wake up, epoll default
Is the LT mode, the buffer in the data is not read away, is triggered every time, therefore, the above code to modify epoll_fd.register (Sys.stdin.fileno (), select. Epollin)
For Epoll_fd.register (Sys.stdin.fileno (), select. Epollin|select. Epollout) is also able to work properly.
Attach the final code:
client.py
#!/usr/pythonImportSOCKET,SYS,SELECTC=Socket.socket (Socket.af_inet,socket. SOCK_STREAM) Host='127.0.0.1'Port=57777C.connect ((host,port)) epoll_fd=Select.epoll () Epoll_fd.register (C.fileno (), select. Epollin) Epoll_fd.register (Sys.stdin.fileno (), select. Epollin) Str="" whiletrue:e_list=Epoll_fd.poll () forFd,eventsinche_list:ifFD = = C.fileno () andevents&Select. Epollin:buf= C.RECV (1024) if notLen (buf): Break Print "ser:", bufifFD = = C.fileno () andEvents &Select. Epollout:#print ' Send msg to ser. 'c.send (str) epoll_fd.modify (C.fileno (), select. Epollin)ifFD = = Sys.stdin.fileno () andEvents &Select. Epollin:str=raw_input ("Me:") epoll_fd.modify (C.fileno (), select. Epollout) C.close ()
Simple server and client-like
Importsocket, Os,select,syshost='127.0.0.1'Port=57777s=Socket.socket (Socket.af_inet,socket. SOCK_STREAM) s.setsockopt (socket. Sol_socket, SOCKET. SO_REUSEADDR,1) S.bind ((Host,port)) S.listen (10) Epoll_obj=Select.epoll () Epoll_obj.register (Sys.stdin.fileno (), select. Epollin)Print 'Wait for Connect'cs,caddr=s.accept () Epoll_obj.register (Cs.fileno (), select. Epollin) Str="" while1: Readylist=Epoll_obj.poll () forFd,eventinchreadylist:ifFD = = Cs.fileno () andEvent &Select. Epollin:buf= CS.RECV (128) if notLen (buf): Cs.close () Break Print "CLI:", bufifFD = = Cs.fileno () andEvent &Select. EPOLLOUT:cs.send (str) epoll_obj.modify (Cs.fileno (), select. Epollin)ifFD = = Sys.stdin.fileno () andevent&Select. Epollin:str=raw_input ("Me:") epoll_obj.modify (Cs.fileno (), select. Epollout)
Python's epoll and epolllt