Python-socket Network Programming

Source: Internet
Author: User

1. The special member method of the class 1.1__doc__ represents the description information of the class

1.2__module__ and __class__

__MODULE__ represents the object of the current operation in that module

__CLASS__ represents the class to which the current operation's object belongs

The 1.3__init__ constructor, when the object is created by the class, automatically triggers the 1.4__del__ destructor, which is automatically triggered when the function execution is complete. Automatic triggering when manually triggering 1.5__call__ object brackets in normal situations

Note: The execution of the construction method is triggered by the creation object, that is: Object = class name; for the execution of the __call__ method

Is triggered by an object followed by parentheses: Object () or Class () ()

1.6__dict__ viewing the member properties of a class or object

1.7__str__ if the __str__ method is defined in a class, the output object automatically triggers its return value

1.8__getitem__,__setitem__,__delitem__

Used for index operations, such as dictionaries, which are obtained, set, deleted, respectively

2. Create Class two ways

#type第一个参数:类名

#type第二个参数:当前类的基类

#type第三个参数:类的成员

The class's build call order is __new__---__call__--and __init__

3. Reflection

There are four ways to do this by using a string or by modifying the program's Running state:

Hasattr to determine whether a property exists

GetAttr Getting properties

SetAttr Setting properties

Delattr Deleting properties

Importing modules as strings

Import importlib __import__ (' Import_lib.metaclass ') #这是解释器自己内部用的 #importlib.import_module (' Import_lib.metaclass ') # As with the above-mentioned effect, the official suggests using this
4. Exception Handling 4.1 isinstance (Obj,class)

Determines whether an object belongs to an instantiated object of this class

4.2 Issubclass (Sub,foo)

Determine if a class is a subclass of another class (derived class)

4.3 Exception types
Attributeerror attempts to access a tree that does not have an object, such as foo.x, but Foo does not have a property xioerror input/output exception; it is basically impossible to open the file Importerror the module or package cannot be introduced is basically a path problem or name error Indentationerror syntax error (subclass); The code is not aligned correctly indexerror the subscript index exceeds the sequence boundary, for example, when X has only three elements, it attempts to access the X[5]keyerror Attempting to access a key that does not exist in the dictionary Keyboardinterrupt CTRL + C is pressed Nameerror use a variable that has not been assigned to the object SyntaxError Python code is illegal, the code cannot compile (personally think this is a syntax error, Wrong) TypeError the incoming object type is not compliant with the requirements Unboundlocalerror attempts to access a local variable that is not yet set, basically because another global variable with the same name causes you to think that you are accessing it valueerror a value that the caller does not expect , even if the type of the value is correct
more Exception Types4.4 Catching all exceptions
Try:    passexcept Exception as e: #捕获所有异常    print (e)
4.5 Abnormal complete structure

Try:    pass# main code block except Exception as E: #捕捉所有异常 (exception, auto trigger)    print (e) #输出异常else:    pass# the main block executes after the code block is completed finally :    pass# will eventually execute this block of code
4.6 Active Trigger exception

Try:    raise Exception (' proactive exception, throw error message ') except Exception as E: #捕捉所有异常 (Presence exception, auto trigger)    print (e) #输出异常finally:    Pass# will eventually execute this block of code
4.7 Custom Exceptions

Class Error_type (Exception): #继承全异常类    def __init__ (self,msg):        self.msg=msg    def __str__ (self):        Return Self.msgtry:    raise Error_type (' Custom exception class, unsolicited exception information ') except Error_type as E:    print (e)
4.8 Assertions

Prompt information. Hint code must meet this condition

Note: The assertion condition is not true and the following code is not executed (throws an exception)

But throws an exception, exception cannot capture the

5. Network Programming 5.1TCP/IP Protocol diagram

5.2 Socket

Sockets are also commonly referred to as "sockets," which describe IP addresses and ports, and are a handle to a chain of communication, where applications usually make requests to the network through "sockets" or respond to network requests.

Sockets originate from UNIX, and one of the basic philosophies of unix/linux is "Everything is file", and the file is operated with "open" "Read and Write" "Off" mode. Socket is an implementation of this pattern, the socket is a special kind of file, some of the socket function is the operation of it (read/write Io, open, close)

The difference between a socket and file:

    • The file module is "open", "Read and write" "Close" for a specified document
    • The socket module is "open", "Read and write" "Off" for server-side and client sockets

Socket ServerSocket Client5.3socket Properties

SK = Socket.socket (socket.af_inet,socket. sock_stream,0)

Parameter one: Address cluster socket.af_inet IPv4 (default) Socket.af_inet6 IPv6 Socket.af_unix can only be used for single UNIX system interprocess communication parameter two: type socket. Sock_stream streaming socket, for TCP (default) socket. SOCK_DGRAM datagram socket, for UDP socket. Sock_raw the original socket, the ordinary socket can not handle ICMP, IGMP and other network messages, and Sock_raw May, second, Sock_raw can also handle special IPV4 messages, in addition, the use of the original socket, can be IP_  The HDRINCL socket option constructs an IP header by the user. Socket. SOCK_RDM is a reliable form of UDP that guarantees the delivery of datagrams but does not guarantee the order. Sock_ram is used to provide low-level access to the original protocol, which is used when certain special operations are required, such as sending ICMP packets.  Sock_ram is typically used only by advanced users or by programs that are run by administrators. Socket. Sock_seqpacket reliable Continuous Packet service parameter three: protocol 0 (default) protocol related to a specific address family, if 0, the system will automatically select an appropriate protocol based on the address format and socket category.
Import Socketip_port = (' 127.0.0.1 ', 9999) SK = Socket.socket (socket.af_inet,socket. sock_dgram,0) Sk.bind (ip_port) while True:    data = SK.RECV (1024x768)    print data
Import Socketip_port = (' 127.0.0.1 ', 9999) SK = Socket.socket (socket.af_inet,socket. sock_dgram,0) while True: INP = raw_input (' data: '). Strip () if InP = = ' exit ': Break Sk.sendto (inp,ip_ Port) Sk.close ()

Sk.bind (Address)

Binds a socket to the specified address, the format of the address is dependent on the address cluster. Address in the form of Ganso (Host,port) under Af_inet

Sk.listen (Backlog)

Start listening for incoming connections. The backlog specifies the maximum number of connections that can be suspended before a connection is rejected. The backlog equals 5, indicating that the kernel is connected to the request, but the server is still not calling Acept to process the maximum number of connections is 5

Sk.setblocking (BOOL)

Whether blocking (default true), if set flase, then accept and recv when the number of data errors

Sk.accept ()

Receives the connection and returns (Conn,address), where Conn is the new socket object, which can be used to receive and send data, address is the connection client addresses, receive TCP client connections (blocked) Wait for client connections

Sk.connect (Address)

Socket connected to address, General address format Ganso (ip,port), return socket.error error if connection error

SK.CONNET_EX (Address)

function as above, but there will be a return value, the connection is successful return 0, the connection fails when the return encoding, for example: 10061

Sk.close ()

Close socket

SK.RECV (Bufsize[,flag])

Receives socket data, the data is returned as a string, the bufsize instruction can receive a maximum length, and flag provides additional information about the message that can often be ignored

Sk.recvfrom (Bufsize[,flag])

Similar to recv (), but the return value is (data,address). Where data contains the string that receives the message, and address is the socket that sends the data

Sk.send (String[,flag])

Sends the data in a string to a connection socket, which is the length of bytes to send, which is less than the byte size of a string, that is, the specified content may not be sent all.

Sk.sendall (String[,flag])

The data in a string is sent to the connected socket, but all data is sent before it is returned. Successful return none, Failure throws an exception, internal call to send via recursive, send all the content

Sk.sendto (string[,flag],address)

Send data to the socket, address is the form (ipaddr,port) of the Ganso, specify the remote address, the return value is the number of bytes sent, the function is mainly used for the UDP protocol

Sk.settimeout (Timeout)

Set the socket operation time-out, timeout is a floating-point number, the unit is a second, the value of none means no time-out, generally, the timeout should be set in the just-created socket, because they may be used for connection operations (such as client connections up to 5s waiting)

Sk.getpeername ()

Returns the remote address of the connection socket, usually Ganso (Ip,port)

Sk.getsockname ()

Returns the connection socket's own address, the return value is usually Ganso (ip,port)

Sk.fileno ()

Socket file Descriptor

# server Import Socketip_port = (' 127.0.0.1 ', 9999) SK = Socket.socket (socket.af_inet,socket. sock_dgram,0) Sk.bind (ip_port) while True:    data, (host,port) = Sk.recvfrom (1024x768)    print (Data,host,port)    Sk.sendto (bytes (' OK ', encoding= ' Utf-8 '), (host,port)) #客户端import Socketip_port = (' 127.0.0.1 ', 9999) SK = Socket.socket ( Socket.af_inet,socket. sock_dgram,0) while True:    INP = input (' data: '). Strip ()    if InP = = ' exit ': Break    sk.sendto (bytes (INP, encoding= ' Utf-8 '), ip_port)    data = Sk.recvfrom (1024x768)    print (data) sk.close ()
using Select monitoring Terminal Operation Exampleuse Select to implement pseudo-simultaneous processing of multiple socket client requests: Serveruse Select to implement pseudo-simultaneous processing of multiple socket client requests: Client

Here the socket server is compared to the native socket, and he supports that when a request is no longer sending data, it will not wait but can process other requested data. However, if each request takes a long time, the server side of the Select version cannot complete the simultaneous operation

implement socket server based on select6.SocketServer Module

The Socketserver internally uses IO multiplexing and "multithreading" and "multi-process" to enable the socket service side to process multiple client requests concurrently. That is, when each client requests a connection to the server, the socket server is creating a "thread" or "process" dedicated to all requests from the current client.

Threadingtcpserver

The Soket server implemented by Threadingtcpserver creates a " thread " For each client that is used to interact with the client.

1. Threadingtcpserver Foundation

Using Threadingtcpserver:

    • Create a class that inherits from Socketserver.baserequesthandler
    • A method called handle must be defined in a class
    • Start Threadingtcpserver

Socketserver Implementing a serverSocketserver implementing the client6.1ThreadingTCPServer Source Code Analysis

The class diagram relationships of Threadingtcpserver are as follows:

The internal invocation process is:

    • Start the service-side program
    • Executes the tcpserver.__init__ method, creates the server-side socket object and binds the IP and port
    • Executes the baseserver.__init__ method to assign a custom inherited class Myrequesthandle from Socketserver.baserequesthandler to Self.requesthandlerclass
    • Executes the Baseserver.server_forever method, while the loop is always listening for client requests to arrive ...
    • When a client connection arrives at the server
    • Executes the Threadingmixin.process_request method, creating a "thread" to handle the request
    • Execute the Threadingmixin.process_request_thread method
    • Executes the Baseserver.finish_request method and executes self. Requesthandlerclass () is the construction method that executes the custom Myrequesthandler (automatically calls the constructor of the base class Baserequesthandler, which in turn calls the Handle method of Myrequesthandler)
6.2 Forkingtcpserver

The use and execution processes of forkingtcpserver and threadingtcpserver are basically consistent, except that "threads" and "processes" are created internally for the requestor.

Service SideClient

The above forkingtcpserver just the code in the Threadingtcpserver instance:

Server = Socketserver.threadingtcpserver ((' 127.0.0.1 ', 8009), Myrequesthandler) changed to: Server = Socketserver.forkingtcpserver ((' 127.0.0.1 ', 8009), Myrequesthandler)

Socketserver's Threadingtcpserver can handle requests at the same time thanks to the select and os.fork two things, essentially creating a process on the server side for each client, Currently the newly created process is used to handle requests from the corresponding client, so you can support simultaneous n client links (long connections).

Reference Links:

Http://www.cnblogs.com/wupeiqi/articles/5040823.html

Http://www.cnblogs.com/wupeiqi/articles/5017742.html

Https://twistedmatrix.com/trac
http://twistedmatrix.com/documents/current/api/

Python-socket Network Programming

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.