In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces "how to use socket's epoll model". In daily operation, I believe many people have doubts about how to use socket's epoll model. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "how to use socket's epoll model". Next, please follow the editor to study!
The select model is good, but it has one drawback: it can only monitor 1024 file descriptors, and although you can get a larger number of monitors by recompiling the kernel, you might as well focus on the more advanced epoll model. In the select model, each time you need to traverse all the file descriptors under monitoring to determine which one is writable and which is readable, so that the more you monitor, the slower the speed, while in the epoll model, all events added to the epoll will establish a callback relationship with the Nic driver. In short, if there is a connection to write, the writable event will be reported to you. And you don't have to ask them one by one which connection is writable and which is readable.
The following example implements the same functionality as the previous example, but more efficiently:
# coding=utf-8
Import socket
Import select
Import sys
From MsgContainer import MsgContainer
Def start_server (port):
Serversocket = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
Serversocket.setsockopt (socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
Serversocket.bind (('0.0.0.0, port))
# accept queue size is 100
Serversocket.listen (100)
Serversocket.setblocking (0)
Epoll = select.epoll ()
# register an in event and wait for data to be read
Epoll.register (serversocket.fileno (), select.EPOLLIN)
Try:
# Save connection, request, and response information
Connections = {}
Message_queues = {} # stores data that can be sent
While True:
# wait up to 1 second. An event returns a list of events.
Events = epoll.poll (1)
For fileno, event in events:
# the handle to the event is server
If fileno = = serversocket.fileno ():
Connection, address = serversocket.accept ()
# set to non-blocking
Connection.setblocking (0)
# newly created connections also register read events
Epoll.register (connection.fileno (), select.EPOLLIN)
Connections [connection.fileno ()] = connection
Message_queues [connection.fileno ()] = MsgContainer ()
# not server, that is the established connection, now the connection is readable
Elif event & select.EPOLLIN:
Data = connections [fileno] .recv (1024)
If data:
Epoll.modify (fileno, select.EPOLLOUT)
Message_ queues [fileno] .add _ data (data)
Else:
Epoll.modify (fileno, 0)
Connections [fileno] .shutdown (socket.SHUT_RDWR)
Del connections [fileno]
Del message_ queues[fileno]
Elif event & select.EPOLLOUT:
# writable events are triggered
If not fileno in message_queues or not fileno in connections:
Continue
Clientsocket = connections [fileno]
Mc = message_ queues [fileno]
Msgs = mc.get_all_msg ()
For msg in msgs:
Msg = mc.pack_msg (msg)
Clientsocket.send (msg)
Mc.clear_msg ()
# the data that needs to be written back has been written, register the read event again
Epoll.modify (fileno, select.EPOLLIN)
Elif event & select.EPOLLHUP:
# was suspended, logged out handle, closed the connection, at this time, the client took the initiative to disconnect
Epoll.unregister (fileno)
If fileno in connections:
Connections [fileno] .close ()
Del connections [fileno]
If fileno in message_queues:
Del message_ queues[fileno]
Finally:
Epoll.unregister (serversocket.fileno ())
Epoll.close ()
Serversocket.close ()
If _ _ name__ = ='_ _ main__':
If len (sys.argv) = = 2:
Port = int (sys.argv [1])
Start_server (port)
Else:
Print u 'Please enter the port number'
Let's look at the code on the client side:
# coding=utf-8
Import sys
Import time
Import datetime
Import socket
Import cPickle
Import threading
From MsgContainer import MsgContainer
Def start_client (addr,port,msgCount):
Mc = MsgContainer ()
PLC_ADDR = addr
PLC_PORT = port
Time_lst = []
S = socket.socket ()
S.connect ((PLC_ADDR, PLC_PORT))
Seconds1 = int (time.time ())
I = 0
While True:
Seconds = int (time.time ())
Microseconds = datetime.datetime.now () .microsecond
Data = {'sec':seconds,'micsec':microseconds}
Data = cPickle.dumps (data)
Data = mc.pack_msg (data)
S.send (data)
Recv_data = s.recv (1024)
Mc.add_data (recv_data)
Msgs = mc.get_all_msg ()
Seconds = int (time.time ())
Microseconds = datetime.datetime.now () .microsecond
For msg in msgs:
Msgdict = cPickle.loads (msg)
Time_lst.append (seconds-msgdict ['sec']) * 1000000 + microseconds-msgdict [' micsec']) / 1000.0)
Mc.clear_msg ()
I + = 1
If I > msgCount:
Print sum (time_lst) / float (len (time_lst))
Break
S.close ()
If _ _ name__ = ='_ _ main__':
If len (sys.argv) = = 4:
Addr = sys.argv [1]
Port = int (sys.argv [2])
MsgCount = int (sys.argv [3])
T_lst = []
For i in range (100):
T = threading.Thread (target=start_client,args= (addr,port,msgCount))
T_lst.append (t)
For t in t_lst:
T.start ()
For t in t_lst:
T.join ()
# start_client ('123.56.190.151) 8091100
On the client side, 100 threads at a time try to establish a connection. If the accept queue size on the server side is set to 10, for example, individual connections cannot be established, so I set it to 100 here.
At this point, the study on "how to use the epoll model of socket" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.