My Python growth path---the eighth Day---Python Foundation---March 5, 2016 (Sunny)

Source: Internet
Author: User

Socketserver

Before the ethical socket module is a single process, only one client connection and request can be accepted, and the connection and request from other clients can be accepted only after the client disconnects. Of course, we can also use the multi-threading module of Python to write a socket that can receive multiple client connections and requests at the same time. But this is not necessary, because the Python standard library has built a multi-threaded socket module Socketserver, we directly call on it, there is absolutely no need to repeat the wheel.

We simply need to retrofit the previous socket demo service side, the client does not change

1234567891011121314151617181920212223242526272829303132333435363738394041 #!/usr/bin/env python3# coding:utf-8‘‘‘Created on: 2016年3月5日@author: 张晓宇Email: [email protected]Version: 1.0 Description: socketserver演示程序Help:‘‘‘import socketserverclass Myserver(socketserver.BaseRequestHandler):    ‘‘‘    定义一个类,这个类要继承自socketserver.BaseRequestHandler    ‘‘‘    def handle(self):        ‘‘‘        重写handle方法,这个非常关键,当server收到客户端的请求,就会为更改客户端单独        启动一个线程并调用该方法处理客户端的请求        ‘‘‘        print(‘New Conn: ‘,self.client_address)        while True:            ‘‘‘            循环接收客户端发送过来的数据,这里可以一            些判断比如接收到的内容为空或发生异常及其            他推出逻辑来退出循环            ‘‘‘            data = self.request.recv(1024)            print(‘Client say: %s‘ %data.decode())            self.request.send(data)if __name__ == ‘__main__‘:    IP_PORT = (‘127.0.0.1‘, 9999) # 定义监听的IP地址和端口    server = socketserver.ThreadingTCPServer(IP_PORT, Myserver) # 创建soeketserver对象,ThreadingTCPServer方法接收两个参数,一个是监听的ip地址和端口,另一个是刚才我们创建的类    server.serve_forever() # 启动服务

See, is not very concise, in fact, Socketserver is a multi-threaded and class technology to the original socket module has been encapsulated, we use it is so simple

My Python growth path---the eighth Day---Python Foundation---March 5, 2016 (Sunny)

Related Article

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.