python server forever 无法继续执行_Python基础篇【第8篇】: Socket编程(二)SocketServer...

1 """Generic socket server classes.2 This module tries to capture the various aspects of defining a server:3 For socket-based servers:4 - address family:5 - AF_INET{,6}: IP (Internet Protocol) sockets (default)6 - AF_UNIX: Unix domain sockets7 - others, e.g. AF_DECNET are conceivable (see 8 - socket type:9 - SOCK_STREAM (reliable stream, e.g. TCP)10 - SOCK_DGRAM (datagrams, e.g. UDP)11

12 For request-based servers (including socket-based):13

14 - client address verification before further looking at the request15 (This is actually a hook for any processing that needs to look16 at the request before anything else, e.g. logging)17 - how to handle multiple requests:18 - synchronous (one request is handled at a time)19 - forking (each request is handled by a new process)20 - threading (each request is handled by a new thread)21

22 The classes in this module favor the server type that is simplest to23 write: a synchronous TCP/IP server. This is bad class design, but24 save some typing. (There's also the issue that a deep class hierarchy25 slows down method lookups.)26

27 There are five classes in an inheritance diagram, four of which represent28 synchronous servers of four types:29

30 +------------+31 | BaseServer |32 +------------+33 |34 v35 +-----------+ +------------------+36 | TCPServer |------->| UnixStreamServer |37 +-----------+ +------------------+38 |39 v40 +-----------+ +--------------------+41 | UDPServer |------->| UnixDatagramServer |42 +-----------+ +--------------------+43

44 Note that UnixDatagramServer derives from UDPServer, not from45 UnixStreamServer -- the only difference between an IP and a Unix46 stream server is the address family, which is simply repeated in both47 unix server classes.48

49 Forking and threading versions of each type of server can be created50 using the ForkingMixIn and ThreadingMixIn mix-in classes. For51 instance, a threading UDP server class is created as follows:52

53 class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass54

55 The Mix-in class must come first, since it overrides a method defined56 in UDPServer! Setting the various member variables also changes57 the behavior of the underlying server mechanism.58

59 To implement a service, you must derive a class from60 BaseRequestHandler and redefine its handle() method. You can then run61 various versions of the service by combining one of the server classes62 with your request handler class.63

64 The request handler class must be different for datagram or stream65 services. This can be hidden by using the request handler66 subclasses StreamRequestHandler or DatagramRequestHandler.67

68 Of course, you still have to use your head!69

70 For instance, it makes no sense to use a forking server if the service71 contains state in memory that can be modified by requests (since the72 modifications in the child process would never reach the initial state73 kept in the parent process and passed to each child). In this case,74 you can use a threading server, but you will probably have to use75 locks to avoid two requests that come in nearly simultaneous to apply76 conflicting changes to the server state.77

78 On the other hand, if you are building e.g. an HTTP server, where all79 data is stored externally (e.g. in the file system), a synchronous80 class will essentially render the service "deaf" while one request is81 being handled -- which may be for a very long time if a client is slow82 to read all the data it has requested. Here a threading or forking83 server is appropriate.84

85 In some cases, it may be appropriate to process part of a request86 synchronously, but to finish processing in a forked child depending on87 the request data. This can be implemented by using a synchronous88 server and doing an explicit fork in the request handler class89 handle() method.90

91 Another approach to handling multiple simultaneous requests in an92 environment that supports neither threads nor fork (or where these are93 too expensive or inappropriate for the service) is to maintain an94 explicit table of partially finished requests and to use select() to95 decide which request to work on next (or whether to handle a new96 incoming request). This is particularly important for stream services97 where each client can potentially be connected for a long time (if98 threads or subprocesses cannot be used).99

100 Future work:101 - Standard classes for Sun RPC (which uses either UDP or TCP)102 - Standard mix-in classes to implement various authentication103 and encryption schemes104 - Standard framework for select-based multiplexing105

106 XXX Open problems:107 - What to do with out-of-band data?108

109 BaseServer:110 - split generic "request" functionality out into BaseServer class.111 Copyright (C) 2000 Luke Kenneth Casson Leighton 112

113 example: read entries from a SQL database (requires overriding114 get_request() to return a table entry from the database).115 entry is processed by a RequestHandlerClass.116

117 """

118

119 #Author of the BaseServer patch: Luke Kenneth Casson Leighton

120

121 #XXX Warning!

122 #There is a test suite for this module, but it cannot be run by the

123 #standard regression test.

124 #To run it manually, run Lib/test/test_socketserver.py.

125

126 __version__ = "0.4"

127

128

129 importsocket130 importselect131 importsys132 importos133 importerrno134 try:135 importthreading136 exceptImportError:137 importdummy_threading as threading138

139 __all__ = ["TCPServer","UDPServer","ForkingUDPServer","ForkingTCPServer",140 "ThreadingUDPServer","ThreadingTCPServer","BaseRequestHandler",141 "StreamRequestHandler","DatagramRequestHandler",142 "ThreadingMixIn", "ForkingMixIn"]143 if hasattr(socket, "AF_UNIX"):144 __all__.extend(["UnixStreamServer","UnixDatagramServer",145 "ThreadingUnixStreamServer",146 "ThreadingUnixDatagramServer"])147

148 def _eintr_retry(func, *args):149 """restart a system call interrupted by EINTR"""

150 whileTrue:151 try:152 return func(*args)153 except(OSError, select.error) as e:154 if e.args[0] !=errno.EINTR:155 raise

156

157 classBaseServer:158

159 """Base class for server classes.160

161 Methods for the caller:162

163 - __init__(server_address, RequestHandlerClass)164 - serve_forever(poll_interval=0.5)165 - shutdown()166 - handle_request() # if you do not use serve_forever()167 - fileno() -> int # for select()168

169 Methods that may be overridden:170

171 - server_bind()172 - server_activate()173 - get_request() -> request, client_address174 - handle_timeout()175 - verify_request(request, client_address)176 - server_close()177 - process_request(request, client_address)178 - shutdown_request(request)179 - close_request(request)180 - handle_error()181

182 Methods for derived classes:183

184 - finish_request(request, client_address)185

186 Class variables that may be overridden by derived classes or187 instances:188

189 - timeout190 - address_family191 - socket_type192 - allow_reuse_address193

194 Instance variables:195

196 - RequestHandlerClass197 - socket198

199 """

200

201 timeout =None202

203 def __init__(self, server_address, RequestHandlerClass):      实例参数最终传递到这里(ip与端口,自定义类)204 """Constructor. May be extended, do not override."""

205 self.server_address =server_address206 self.RequestHandlerClass =RequestHandlerClass207 self.__is_shut_down =threading.Event()208 self.__shutdown_request =False209

210 defserver_activate(self):211 """Called by constructor to activate the server.212

213 May be overridden.214

215 """

216 pass

217

218 def serve_forever(self, poll_interval=0.5):219 """Handle one request at a time until shutdown.220

221 Polls for shutdown every poll_interval seconds. Ignores222 self.timeout. If you need to do periodic tasks, do them in223 another thread.224 """

225 self.__is_shut_down.clear()226 try:227 while not self.__shutdown_request:228 #XXX: Consider using another file descriptor or

229 #connecting to the socket to wake this up instead of

230 #polling. Polling reduces our responsiveness to a

231 #shutdown request and wastes cpu at all other times.

232 r, w, e =_eintr_retry(select.select, [self], [], [],233 poll_interval)234 if self inr:235 self._handle_request_noblock()236 finally:237 self.__shutdown_request =False238 self.__is_shut_down.set()239

240 defshutdown(self):241 """Stops the serve_forever loop.242

243 Blocks until the loop has finished. This must be called while244 serve_forever() is running in another thread, or it will245 deadlock.246 """

247 self.__shutdown_request =True248 self.__is_shut_down.wait()249

250 #The distinction between handling, getting, processing and

251 #finishing a request is fairly arbitrary. Remember:

252 #253 #- handle_request() is the top-level call. It calls

254 #select, get_request(), verify_request() and process_request()

255 #- get_request() is different for stream or datagram sockets

256 #- process_request() is the place that may fork a new process

257 #or create a new thread to finish the request

258 #- finish_request() instantiates the request handler class;

259 #this constructor will handle the request all by itself

260

261 defhandle_request(self):262 """Handle one request, possibly blocking.263

264 Respects self.timeout.265 """

266 #Support people who used socket.settimeout() to escape

267 #handle_request before self.timeout was available.

268 timeout =self.socket.gettimeout()269 if timeout isNone:270 timeout =self.timeout271 elif self.timeout is notNone:272 timeout =min(timeout, self.timeout)273 fd_sets = _eintr_retry(select.select, [self], [], [], timeout)        #调用select模块实现了多线程

274 if notfd_sets[0]:275 self.handle_timeout()276 return

277 self._handle_request_noblock()278

279 def_handle_request_noblock(self):280 """Handle one request, without blocking.281

282 I assume that select.select has returned that the socket is283 readable before this function was called, so there should be284 no risk of blocking in get_request().285 """

286 try:287 request, client_address =self.get_request()288 exceptsocket.error:289 return

290 ifself.verify_request(request, client_address):291 try:292 self.process_request(request, client_address)293 except:294 self.handle_error(request, client_address)295 self.shutdown_request(request)296

297 defhandle_timeout(self):298 """Called if no new request arrives within self.timeout.299

300 Overridden by ForkingMixIn.301 """

302 pass

303

304 defverify_request(self, request, client_address):305 """Verify the request. May be overridden.306

307 Return True if we should proceed with this request.308

309 """

310 returnTrue311

312 defprocess_request(self, request, client_address):313 """Call finish_request.314

315 Overridden by ForkingMixIn and ThreadingMixIn.316

317 """

318 self.finish_request(request, client_address)319 self.shutdown_request(request)320

321 defserver_close(self):322 """Called to clean-up the server.323

324 May be overridden.325

326 """

327 pass

328

329 deffinish_request(self, request, client_address):330 """Finish one request by instantiating RequestHandlerClass."""

331 self.RequestHandlerClass(request, client_address, self)332

333 defshutdown_request(self, request):334 """Called to shutdown and close an individual request."""

335 self.close_request(request)336

337 defclose_request(self, request):338 """Called to clean up an individual request."""

339 pass

340

341 defhandle_error(self, request, client_address):342 """Handle an error gracefully. May be overridden.343

344 The default is to print a traceback and continue.345

346 """

347 print '-'*40

348 print 'Exception happened during processing of request from',349 printclient_address350 importtraceback351 traceback.print_exc() #XXX But this goes to stderr!

352 print '-'*40

353

354

355 class TCPServer(BaseServer):   ThreadingTCPServer基类之一,它又有自己的基类BaseServer   """Base class for various socket-based server classes.356

357 Defaults to synchronous IP stream (i.e., TCP).358

359 Methods for the caller:360

361 - __init__(server_address, RequestHandlerClass, bind_and_activate=True)362 - serve_forever(poll_interval=0.5)363 - shutdown()364 - handle_request() # if you don't use serve_forever()365 - fileno() -> int # for select()366

367 Methods that may be overridden:368

369 - server_bind()370 - server_activate()371 - get_request() -> request, client_address372 - handle_timeout()373 - verify_request(request, client_address)374 - process_request(request, client_address)375 - shutdown_request(request)376 - close_request(request)377 - handle_error()378

379 Methods for derived classes:380

381 - finish_request(request, client_address)382

383 Class variables that may be overridden by derived classes or384 instances:385

386 - timeout387 - address_family388 - socket_type389 - request_queue_size (only for stream sockets)390 - allow_reuse_address391

392 Instance variables:393

394 - server_address395 - RequestHandlerClass396 - socket397

398 """

399

400 address_family =socket.AF_INET401

402 socket_type =socket.SOCK_STREAM403

404 request_queue_size = 5

405

406 allow_reuse_address =False407

408 def __init__(self, server_address, RequestHandlerClass, bind_and_activate=True):409 """Constructor. May be extended, do not override."""

410 BaseServer.__init__(self, server_address, RequestHandlerClass)        调用它自己基类函数BaseServer的初始化函数进行多线程的启动411 self.socket =socket.socket(self.address_family,self.socket_type)      创建启动的独立线程socket412 ifbind_and_activate:413 try:414 self.server_bind()415 self.server_activate()416 except:417 self.server_close()418 raise

419

420 defserver_bind(self):421 """Called by constructor to bind the socket.422

423 May be overridden.424

425 """

426 ifself.allow_reuse_address:427 self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)428 self.socket.bind(self.server_address)                    绑定地址429 self.server_address =self.socket.getsockname()430 defserver_activate(self):431 """

432 Called by constructor to activate the server. May be overridden.可以被重构433 """

434 self.socket.listen(self.request_queue_size)                 端口检听435

436 defserver_close(self):437 """Called to clean-up the server.438 May be overridden.439 """

440 self.socket.close()                              关闭socket441

442 deffileno(self):443 """Return socket file number.444

445 Interface required by select().446

447 """

448 returnself.socket.fileno()449

450 defget_request(self):451 """Get the request and client address from the socket.452 May be overridden.453 """

454 returnself.socket.accept()455

456 defshutdown_request(self, request):457 """Called to shutdown and close an individual request."""

458 try:459 #explicitly shutdown. socket.close() merely releases

460 #the socket and waits for GC to perform the actual close.

461 request.shutdown(socket.SHUT_WR)462 exceptsocket.error:463 pass #some platforms may raise ENOTCONN here

464 self.close_request(request)465

466 defclose_request(self, request):467 """Called to clean up an individual request."""

468 request.close()469

470

471 classUDPServer(TCPServer):472

473 """UDP server class."""

474

475 allow_reuse_address =False476

477 socket_type =socket.SOCK_DGRAM478

479 max_packet_size = 8192

480

481 defget_request(self):482 data, client_addr =self.socket.recvfrom(self.max_packet_size)483 return(data, self.socket), client_addr484

485 defserver_activate(self):486 #No need to call listen() for UDP.

487 pass

488

489 defshutdown_request(self, request):490 #No need to shutdown anything.

491 self.close_request(request)492

493 defclose_request(self, request):494 #No need to close anything.

495 pass

496

497 classForkingMixIn:498

499 """Mix-in class to handle each request in a new process."""

500

501 timeout = 300

502 active_children =None503 max_children = 40

504

505 defcollect_children(self):506 """Internal routine to wait for children that have exited."""

507 if self.active_children isNone:508 return

509

510 #If we're above the max number of children, wait and reap them until

511 #we go back below threshold. Note that we use waitpid(-1) below to be

512 #able to collect children in size() syscalls instead

513 #of size(): the downside is that this might reap children

514 #which we didn't spawn, which is why we only resort to this when we're

515 #above max_children.

516 while len(self.active_children) >=self.max_children:517 try:518 pid, _ = os.waitpid(-1, 0)519 self.active_children.discard(pid)520 exceptOSError as e:521 if e.errno ==errno.ECHILD:522 #we don't have any children, we're done

523 self.active_children.clear()524 elif e.errno !=errno.EINTR:525 break

526

527 #Now reap all defunct children.

528 for pid inself.active_children.copy():529 try:530 pid, _ =os.waitpid(pid, os.WNOHANG)531 #if the child hasn't exited yet, pid will be 0 and ignored by

532 #discard() below

533 self.active_children.discard(pid)534 exceptOSError as e:535 if e.errno ==errno.ECHILD:536 #someone else reaped it

537 self.active_children.discard(pid)538

539 defhandle_timeout(self):540 """Wait for zombies after self.timeout seconds of inactivity.541

542 May be extended, do not override.543 """

544 self.collect_children()545

546 defprocess_request(self, request, client_address):547 """Fork a new subprocess to process the request."""

548 self.collect_children()549 pid =os.fork()550 ifpid:551 #Parent process

552 if self.active_children isNone:553 self.active_children =set()554 self.active_children.add(pid)555 self.close_request(request) #close handle in parent process

556 return

557 else:558 #Child process.

559 #This must never return, hence os._exit()!

560 try:561 self.finish_request(request, client_address)562 self.shutdown_request(request)563 os._exit(0)564 except:565 try:566 self.handle_error(request, client_address)567 self.shutdown_request(request)568 finally:569 os._exit(1)570

571

572 classThreadingMixIn:          基类2573 """Mix-in class to handle each request in a new thread."""

574

575 #Decides how threads will act upon termination of the

576 #main process

577 daemon_threads =False578

579 defprocess_request_thread(self, request, client_address):580 """Same as in BaseServer but as a thread.581

582 In addition, exception handling is done here.583

584 """

585 try:586 self.finish_request(request, client_address)587 self.shutdown_request(request)588 except:589 self.handle_error(request, client_address)590 self.shutdown_request(request)591

592 defprocess_request(self, request, client_address):593 """Start a new thread to process the request."""

594 t = threading.Thread(target =self.process_request_thread,595 args =(request, client_address))596 t.daemon =self.daemon_threads597 t.start()598

599

600 class ForkingUDPServer(ForkingMixIn, UDPServer): pass

601 class ForkingTCPServer(ForkingMixIn, TCPServer): pass

602

603 class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass

604 class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass

605

606 if hasattr(socket, 'AF_UNIX'):607

608 classUnixStreamServer(TCPServer):609 address_family =socket.AF_UNIX610

611 classUnixDatagramServer(UDPServer):612 address_family =socket.AF_UNIX613

614 class ThreadingUnixStreamServer(ThreadingMixIn, UnixStreamServer): pass

615

616 class ThreadingUnixDatagramServer(ThreadingMixIn, UnixDatagramServer): pass

617

618 classBaseRequestHandler:619 自定义MyServer自继承这里,主要用于处理来自每个线程的请求,函数拥有三个方法,但是每个方法的结构体都没pass,所以我们在继承以后需要对方法进行重构。620 """Base class for request handler classes.621

622 This class is instantiated for each request to be handled. The623 constructor sets the instance variables request, client_address624 and server, and then calls the handle() method. To implement a625 specific service, all you need to do is to derive a class which626 defines a handle() method.627

628 The handle() method can find the request as self.request, the629 client address as self.client_address, and the server (in case it630 needs access to per-server information) as self.server. Since a631 separate instance is created for each request, the handle() method632 can define arbitrary other instance variariables.633 """

634

635 def __init__(self, request, client_address, server):    接收请求request,客户端地址client_address,自定义server636 self.request =request                   分别赋值637 self.client_address =client_address638 self.server =server639 self.setup()                         首先执行setup()函数640 try:641 self.handle()                      再执行handle()642 finally:643 self.finish()                      最后执行finish()644

645 defsetup(self):              三个函数结构体都为pass ,需要在继承时进行方法重构646 pass

647

648 defhandle(self):649 pass

650

651 deffinish(self):652 pass

653

654

655 #The following two classes make it possible to use the same service

656 #class for stream or datagram servers.

657 #Each class sets up these instance variables:

658 #- rfile: a file object from which receives the request is read

659 #- wfile: a file object to which the reply is written

660 #When the handle() method returns, wfile is flushed properly

661

662

663 classStreamRequestHandler(BaseRequestHandler):664

665 """Define self.rfile and self.wfile for stream sockets."""

666

667 #Default buffer sizes for rfile, wfile.

668 #We default rfile to buffered because otherwise it could be

669 #really slow for large data (a getc() call per byte); we make

670 #wfile unbuffered because (a) often after a write() we want to

671 #read and we need to flush the line; (b) big writes to unbuffered

672 #files are typically optimized by stdio even when big reads

673 #aren't.

674 rbufsize = -1

675 wbufsize =0676

677 #A timeout to apply to the request socket, if not None.

678 timeout =None679

680 #Disable nagle algorithm for this socket, if True.

681 #Use only when wbufsize != 0, to avoid small packets.

682 disable_nagle_algorithm =False683

684 defsetup(self):685 self.connection =self.request686 if self.timeout is notNone:687 self.connection.settimeout(self.timeout)688 ifself.disable_nagle_algorithm:689 self.connection.setsockopt(socket.IPPROTO_TCP,690 socket.TCP_NODELAY, True)691 self.rfile = self.connection.makefile('rb', self.rbufsize)692 self.wfile = self.connection.makefile('wb', self.wbufsize)693

694 deffinish(self):695 if notself.wfile.closed:696 try:697 self.wfile.flush()698 exceptsocket.error:699 #An final socket error may have occurred here, such as

700 #the local error ECONNABORTED.

701 pass

702 self.wfile.close()703 self.rfile.close()704

705

706 classDatagramRequestHandler(BaseRequestHandler):707

708 #XXX Regrettably, I cannot get this working on Linux;

709 #s.recvfrom() doesn't return a meaningful client address.

710

711 """Define self.rfile and self.wfile for datagram sockets."""

712

713 defsetup(self):714 try:715 from cStringIO importStringIO716 exceptImportError:717 from StringIO importStringIO718 self.packet, self.socket =self.request719 self.rfile =StringIO(self.packet)720 self.wfile =StringIO()721

722 deffinish(self):723 self.socket.sendto(self.wfile.getvalue(), self.client_address)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值