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


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.