Use epoll in Python to develop server programs

Source: Internet
Author: User
Python code: Import socket, logging
Import select, errno

Logger = logging. getlogger ("network-server ")

Def initlog ():
Logger. setlevel (logging. Debug)

FH = logging. filehandler ("network-server.log ")
FH. setlevel (logging. Debug)
Ch = logging. streamhandler ()
Ch. setlevel (logging. Error)

Formatter = logging. formatter ("% (asctime) S-% (name) S-% (levelname) S-% (Message) s ")
Ch. setformatter (formatter)
FH. setformatter (formatter)

Logger. addhandler (FH)
Logger. addhandler (CH)

If _ name _ = "_ main __":
Initlog ()

Try:
Listen_fd = socket. socket (socket. af_inet, socket. sock_stream, 0)
Failed t socket. error, MSG:
Logger. Error ("Create a socket failed ")

Try:
Listen_fd.setsockopt (socket. sol_socket, socket. so_reuseaddr, 1)
Failed t socket. error, MSG:
Logger. Error ("setsocketopt error ")

Try:
Listen_fd.bind ('', 2003 ))
Failed t socket. error, MSG:
Logger. Error ("Listen File ID bind IP error ")

Try:
Listen_fd.listen (10)
Failed t socket. error, MSG:
Logger. Error (MSG)

Try:
Epoll_fd = select. epoll ()
Epoll_fd.register (listen_fd.fileno (), select. epollin)
Before t select. error, MSG:
Logger. Error (MSG)

Connections = {}
Addresses = {}
Datalist = {}
While true:
Epoll_list = epoll_fd.poll ()
For FD, events in epoll_list:
If FD = listen_fd.fileno ():
Conn, ADDR = listen_fd.accept ()
Logger. debug ("Accept connection from % s, % d, FD = % d" % (ADDR [0], ADDR [1], conn. fileno ()))
Conn. setblocking (0)
Epoll_fd.register (conn. fileno (), select. epollin | select. epollet)
Connections [conn. fileno ()] = Conn
Addresses [conn. fileno ()] = ADDR
Elif select. epollin & events:
Datas =''
While true:
Try:
Data = Connections [FD]. Recv (10)
If not data and not datas:
Epoll_fd.unregister (FD)
Connections [FD]. Close ()
Logger. debug ("% s, % d Closed" % (addresses [FD] [0], addresses [FD] [1])
Break
Else:
Datas + = Data
Failed t socket. error, MSG:
If msg. errno = errno. eagain:
Logger. debug ("% s receive % s" % (FD, datas ))
Datalist [FD] = datas
Epoll_fd.modify (FD, select. epollet | select. epollout)
Break
Else:
Epoll_fd.unregister (FD)
Connections [FD]. Close ()
Logger. Error (MSG)
Break
Elif select. epollhup & events:
Epoll_fd.unregister (FD)
Connections [FD]. Close ()
Logger. debug ("% s, % d Closed" % (addresses [FD] [0], addresses [FD] [1])
Elif select. epollout & events:
Sendlen = 0
While true:
Sendlen + = Connections [FD]. Send (datalist [FD] [sendlen:])
If sendlen = Len (datalist [FD]):
Break
Epoll_fd.modify (FD, select. epollin | select. epollet)
Else:
Continue

Client Program, Python code:

Import socket
Import time
Import Logging

Logger = logging. getlogger ("network-client ")
Logger. setlevel (logging. Debug)

FH = logging. filehandler ("network-client.log ")
FH. setlevel (logging. Debug)
Ch = logging. streamhandler ()
Ch. setlevel (logging. Error)

Formatter = logging. formatter ("% (asctime) S-% (name) S-% (levelname) S-% (Message) s ")
Ch. setformatter (formatter)
FH. setformatter (formatter)

Logger. addhandler (FH)
Logger. addhandler (CH)

If _ name _ = "_ main __":
Try:
Connfd = socket. socket (socket. af_inet, socket. sock_stream, 0)
Failed t socket. error, MSG:
Logger. Error (MSG)

Try:
Connfd. Connect ("192.168.31.226", 2003 ))
Logger. debug ("connect to network server success ")
Failed t socket. error, MSG:
Logger. Error (MSG)

For I in range (1, 11 ):
Data = "the number is % d" % I
If connfd. Send (data )! = Len (data ):
Logger. Error ("send data to network server failed ")
Break
Readdata = connfd. Recv (1024)
Print readdata
Time. Sleep (1)

Connfd. Close ()

This is a very simple C/S model program. In fact, the process is not much different from the C language, just to learn the basic syntax in Python and the use of the logging, select, and socket modules. The client sends a string, and the server returns the string to the client, which is triggered by the edge used in epoll.

This is an authoritative article about this.
Http://scotdoyle.com/python-epoll-howto.html
Attachment

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.