The Sockeserver module in Python is simple and practical

Source: Internet
Author: User

1, socketserver module Introduction


In Python socket programming, the practical socket module is not possible to implement multiple connections, of course, if the addition of other modules is possible, such as the Select module, here to see the introduction of the next Socketserver module.


Socketserver, look at its name, know is a socket of the server module, in this module, is mainly to implement the server class related functions, in which, that is, the socket module and select module is encapsulated, thus creating a number of base classes for people to use.


2, Socketserver server side and client code

In the Socketserver module, the main thing is to use some server classes to simplify the socket network programming method, first on the basic server code:

#!/usr/bin/env python

import socketserver
import time


HOST = ' 192.168.1.60 '
PORT = 9999

class MyHandler (Socketserver.baserequesthandler):
    def handle (self): while
        True:
            data = SELF.REQUEST.RECV ( 1024)
            Print data,self.client_address
            self.request.send ('%s '% (Data,time.ctime ()))
            If data = ' exit ':
                break

s = Socketserver.threadingtcpserver ((host,port), MyHandler)
s.serve_forever ()

In the above code, only a few things to do, first defined a class, that is, processing the request class, from the base class Baserequesthandler inheritance, mainly to rewrite the handle method, tell the server how to handle the client's request.

Then create a thread of the TCP server class, that is, through multithreading to answer the client, and then use the running method is serve_forever.


The client code is as follows:

#!/usr/bin/env python

import socket

HOST = ' 192.168.1.60 '
PORT = 9999

s = socket.socket ()
S.connect (host,port) while
True:
    kel = raw_input (' >>> ')
    S.sendall (Kel)
    print s.recv ( 1024)
    if Kel = = ' exit ': Break
S.close ()
The code for the client is basically the same as the code for the socket programming, because in the Socketserver module, the main thing is to create the Socke server, without involving the client, so that the client does not need to modify the code to run it.


The difference between this code and the socket programming is that you can communicate with multiple client side at the same time.

[Root@python 514]# ps-ef|grep python
root      8628  6091  0 12:56 pts/3 00:00:00    python server.py< C17/>root      8629 32625  0 12:56 pts/0    00:00:00 python client.py
root      8656  8634  0 12:56 pts/1    00:00:00 python client.py

In a simple socket encoding, only one can communicate at the same time, and other connections will be blocked.


3, Socketserver module class Introduction

In the Socketserver, the default request processor is to receive the connection, get the request, and then close the connection, which means that the client must reconnect every time it loops.

In the code above, the method of event handling is overridden by handle, where loops are used, which means that the connection to the client is maintained.


The base class for the request processing is Baserequesthandler, where the general overriding method is the handle method, mainly how to handle the next request, in which there are three main methods, one is the Setup,handle and the Finish method, When calling this class, first call setup to do some initialization work, and then call the handle method to process the request, and then call the finish method, do some close connection or something In this, the main parameter self.request, that is, the requested socket object, which can send messages Sendall or send, receive the message recv

There are two subclasses in the request processing, one is Sreamrequesthandle and Datagramrequesthandle, in which the base class's Setup method and the finish method are rewritten, and the handle method is not overridden, Because this is left to the user to do the processing request, here are several parameters, a self.rfile used to read the data handle, and Self.wfile is used to send the handle of the message.

When using Rfile and wfile, it is necessary to note that when the client sends a message, it needs to add a carriage return, while the server side needs to use the ReadLine method for reading, that is, to read a row, as follows the server-side code:

#!/usr/bin/env python

import socketserver
import time


HOST = ' 192.168.1.60 '
PORT = 9999

class MyHandler (Socketserver.streamrequesthandler):
    def handle (self): while
        True:
            data = Self.rfile.readline (). Strip ()
            print data,self.client_address
            self.wfile.write ('%s '% (Data,time.ctime ()))
            if data = = ' Exit ':
                break

s = Socketserver.threadingtcpserver ((host,port), MyHandler)
s.serve_forever ()
When using Rfile, you need to use the ReadLine method, otherwise you will be stuck with the processing of the request, while the client code is as follows:

#!/usr/bin/env python

import socket

HOST = ' 192.168.1.60 '
PORT = 9999

s = socket.socket ()
S.connect (host,port) while
True:
#    s = socket.socket ()
# S.connect (    (host,port))
    Kel = Raw_input (' >>> ')
    S.sendall (kel + ' \ n ')
    print s.recv (1024)
    if Kel = ' exit ':
        break< C29/>s.close ()
In the Sendall data, you need to add ' \ n ' to indicate the end of the data sent.


The most basic class is the server class Baseserver class, which defines the relevant method, cannot use this class directly, can only be used for inheritance, two in subclasses, are used as synchronous server classes, TCPServer and Udpserver, These two classes are basically the same when programming with the socket, which is blocking the connection. TCPServer has a subclass of Unixstreamserver, Udpserver has a subclass of Unixdatagramserver, and in the last two subclasses, it is a TCP and UDP server based on file synchronization.


Two mixed classes, one is forkingmixin, mainly with fork, to produce a new process to deal with; one is ThreadingMixIn, produces a new thread, is mainly used to provide the ability of asynchronous processing, the remaining tcpserver and udpserver combination, New four classes are generated, providing the ability to handle asynchronous processing.


When working with mixed classes and server classes, be aware that mixed classes need to be written in the first place, because the mixed classes override the server class's methods, and thus need to be placed at the top.


Summarize:

the Socketserver module in Python is used primarily to provide server classes and to provide the ability to handle asynchronous processing.







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.