Gevent学习之阻塞与非阻塞
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
在线学习好工作/
Gevent学习之阻塞与非阻塞
gevent中一个很大的改进就是将阻塞IO改为非阻塞IO,比如
gevent.socket.patch就是将项目中阻塞socket变为非阻塞,因此深刻理解网络IO 部分阻塞/非阻塞十分重要。
1.阻塞调用是指调用结果返回之前,当前线程会被挂起。函数只有在得到结果之后才会返回
1)connect阻塞
2)接收数据阻塞
2.非阻塞指在不能立刻得到结果之前,该函数不会阻塞当前线程,而会立刻返回
1)接收数据非阻塞
2)非阻塞面临的问题
源码
1.代码示例
import logging
import time
import errno
logging.basicConfig( level=logging.DEBUG ,
format='%( name ) s : % ( message ) s ' , )
if __name__ == '__main__':
import socket
ip = ' localhost '
port = 58562
logger = logging.getLogger ( ' client ' )
# Connect to the server
logger.debug( ' creating socket ' )
s = socket.socket ( socket.AF_INET, socket.SOCK_STREAM ) logger.debug( ' connecting to server ' )
s.setblocking(0)
try:
s.connect( ( ip , port ) )
except socket.error , msg :
if msg[0] != errno.EINPROGRESS :
logger.debug( ' error ' )
exit(1)
#time.sleep(1)
# Send the data
message = ' Hello , world '
#len_sent = s.send ( message )
logger.debug( ' sending data: "%s"', message )
while True :
try:
len_sent = s.send ( message )
break
except socket.error, msg :
if msg[0] != errno.EAGAIN:
exit(1)
# Receive a response
logger.debug( ' waiting for response ' )
while True:
try:
response = s.recv( len_sent )
break
except socket.error, msg:
if msg[0] != errno.EAGAIN:
exit(1)
logger.debug( ' response from server: "%s"', response )
# Clean up
logger.debug( ' closing socket ' )
s.close()
logger.debug( ' done ' )
执行结果
2.代码示例
import logging
import sys
import SocketServer
import time
logging.basicConfig(level=logging.DEBUG ,
format='%( name ) s : % ( message ) s ' ,
)
class EchoRequestHandler ( SocketServer.BaseRequestHandler ) :
def __init__( self , request , client_address , server ) :
self.logger = logging.getLogger ( ' EchoRequestHandler ' )
self.logger.debug( ' __init__ ' )
SocketServer.BaseRequestHandler.__init__(self, request, client_address, server)
return
def setup ( self ) :
self.logger.debug( ' setup ' )
return SocketServer.BaseRequestHandler.setup ( self )
def handle ( self ) :
self.logger.debug( ' handle ' )
# Echo the back to the client
data = self.request.recv ( 1024 )
self.logger.debug( ' recv()->"%s"', data )
self.request.send( data )
return
def finish ( self ) :
self.logger.debug( ' finish ' )
return SocketServer.BaseRequestHandler.finish(self)
class EchoServer(SocketServer.TCPServer):
def __init__(self, server_address, handler_class=EchoRequestHandler):
self.logger = logging.getLogger (' EchoServer ' )
Self.logger.debug ('__init__')
SocketServer.TCPServer.__init__(self, server_address, handler_class)
return
def server_activate ( self ) :
Self.logger.debug ( ' server_activate ' )
SocketServer.TCPServer.server_activate ( self )
return
def serve_forever ( self ) :
self.logger.debug( ' waiting for reques t ' )
( ' Handling requests , press
while True :
self.handle_request()
return