Python network programming (weekly Summary1)

Source: Internet
Author: User
Tags bitwise decimal to hex get ip response code

What is the purpose of the network?     For information transmission, acceptance   can link the information of various points, polygons and bodies to the shared OSI model:    Application layer: Provider service     presentation layer: Data encryption, optimization, compression     Session Layer: Establish link, transport service     Transport layer: Provide data transfer service     Network layer: Routing network interconnection     Overlay: Link Exchange     physical layer: Hard components, interfaces, network card requirements      features:        functions are separated to achieve high cohesion low coupling         make development clearer   What is a network protocol?     is a set of rules, conventions, standards      protocols used by each model:    application layer: TFTP (file transfer), HTTP (Hypertext Transfer Protocol), DNS ( Domain name resolution), SMTP (mail transport)     Transport layer: TCP (for reliable transport services with links), UDP (non-connected transport dependent service)     Network layer: IP (IP address) Common IPV4: Dotted decimal     Value 0~256 (32-bit)   ipv6::128 bit     Physical layer:ieee   special ip:   127.0.0.1      native ip   0.0.0.0        automatically use locally available network cards ip   192.168.1.0    represent network segments    192.168.1.1    typically gateway address    192.198.1.255  broadcast address   port:  value range 1~65535   1~255      Some general-purpose ports   256~1023    SystemsPorts   1024~65535 own ports  linux command:     ifconfig    View native ip     ping ip    View Latency      ps-aux    View system process information      chmod      Set file permissions   &NB Sp  nice-9 ./hello.py  run with 9 priority      pstree      View process tree      ps-ajx& nbsp   View Parent-child process idlinux under File type:      bcd-lsp         b (fast   device file)     &nbs P    c (character device files)         &NBSP;D (catalogue)          -(normal file)     &NBSP ;    l (link file)          s (socket file)          p (pipeline file)  ps-aux& nbsp Stat of   Query result indicates process status:    d  wait state   block   non-interruptible wait state     s  wait state   sleep   interruptible wait State &nb Sp   t  Wait state   pause   Pause execution     r  run (ready state)     z  zombie       +  ago Process (running at terminal) &NBSp     <  higher priority processes       n  lower-priority processes        s  reply-to-group        l  child process link     process priority:        value range:-20~19   -20 Max    Python Socket Module      socket.gethostname ()   Get native name      socket.gethostbyname ("hostname")     Get ip     soccket.gethostbtname ("IP") from the hostname   get the 16 binary conversion:  of the local ipip   Socket.inet_aton (IP)         decimal to hex     SOCKET.INET_ATOA (hex) hexadecimal to decimal     Socket.gethostbyaddr (' 127.0.0.1 ')       return value: Tuple (host, alias, IP address)     Socket.getservbyname ("program name")     Get program ports    Sockets: Sockets programming excuses provided by programming language   Transport Layer Services:    TCP: (SOCK_STREAM)       Reliable transport services for linked     streaming sockets       1. Creating sockets:             socket = Socke T.socket ()       2. Binding address:        &NBSP;    socket.bind      3. Set monitoring:             socket.listen ()       4. Waiting for client links:            socket.accept ()       5. Messaging:            SOCKET.RECV (4096)             socket.send ("")   &NBSP ;   6. Close socket:            Socket.close ()       client:      &NBSP ;  1. Creating sockets             Socket.socket.socket ()         &NBSP;2. Initiating links & nbsp              socket.connect (address)          3. Messaging     &N Bsp         &NBSP;SOCKET.RECV (1024x768)   Close news                socket . Send ("")     send messages                socket.sendall ():      &NB Sp            Things send messages successfully return none failed exception           4. Close socket         & nbsp       Socket.close ()       recv features:            Building the other end of the link is broken and returns a Empty string   fetch content from buffer       Send attribute:            Other end impure in producing a pipe broken exception   to buffer Write content       buffers:            reduce and interact with disk to coordinate data delivery   efficiency       Sticky pack: &nbs P           Because TCP is a data flow socket each time the data is sent between             No boundary one time to fetch the next data will form a sticky package & nbsp;    UDP: (sock_dgram)       non-connected unreliable transport service datagram sockets       1. Creating Sockets:    & nbsp       socket = Socket.socket (af_inet,sock_dgram)       2. Binding address:        &NB Sp   Socket.bind ()       3. Send and receive messages:            Socket.recvfrom ()     & nbsp &nbsP     Socket.sento ()       4. Close socket:            socket.close ()   &N Bsp   Client:          1. Create socket:            socket = Socket.socket () &n Bsp         2. Send and receive messages;            Socket.recvform ()             Socket.sendto ("", address)           3. Close socket:            SO Cket.close ()  sys.argv () command line get parameter return value:    tuple: sys.argv[0] Start   space delimited quotation marks     Socket property method:       Socket Properties:            socket.type      Address type:    &NB Sp       socket.family      Socket IO descriptor:            Socket.fileno () & nbsp           System IO descriptor:               sys.stdin = 0  &nbs P   &nbsp        sys.stdout = 1               sys.stderr = 2  &nbsp ;   Get socket address:             socket.getsockname ()       GET socket client Address:              socket.getpeername ()       set up port reuse:      &NBSP ;      socket.setsockopt (Sol_socket, SO_REUSEADDR, 1)       GET socket option values:      & nbsp      socket.getsockopt ()       set to non-blocking status:              Socket.setblocking (False)       Timeout detection:              Socket.settimeout (SEC)  http Protocol (Hypertext Transfer Protocol):      Web browser a protocol to get a webpage       and all www. Files must comply with this standard  http request:      1. Request Line:            Description of specific request categories and content            GET       /INDEX.HTML&NBsp  /http/1.1          request category       request content         protocol version  &nbsp ;     Request category:         GET:              Get network resources   &NB Sp      POST:            Submit certain additional data          HEAD:  & nbsp       Get response header          PUT:              Update server resource &NB Sp        DELETE:        Delete server resources          CONNECT:  &nbs p; not used          TRACE:          for testing          optio ns:    Get server performance information       2. Request Header:            Request specific description     &NBSP ; 3. Blank line       4. Request Body:            specific parameters or submitted content HTTP response:      1. Response Line: Feedback specific The ringDue           http/1.1     20       OK      &NBS P   Version Agreement     Response Code     additional information         response:          &NBSP;1XX: Indicates that the request has been received           &NBSP;2XX: Response success             3XX: Response needs to be directed (re-record link to third party link)           &NBSP;4XX: Client error             5XX: Server-side error       2. Response header:          Detailed description of response content       3. Blank line     &N Bsp 4. Response Body:          return client request content  IO:    The operation of data exchange in memory can be considered as IO operation (input/output)     IO Intensive program:          Lots of IO operations, consumes less CPU     CPU-intensive programs:          A lot of memory CPU operation, IO relatively less IO classification:    blocking io:        Because some conditions are not achieved cause the program to jam such as: input function     non-blocking IO:         Change the state of the blocking function to block IO multiplexing:    &NBSPThrough a monitoring       monitoring of the behavior of multiple IO events,      which IO event is ready to execute which IO event io is ready:      Critical state when IO event is about to occur   select module        Monitoring IO events       RS, WS, XS = select (Rlist, Wlist, xlist[, timeout])       rlist:  pending io      wlist:  actively processing io      X list:  error io  bit operation to be processed:    bitwise operation according to Bits     & press as with    |  bitwise OR     ^      << left XOR     >> Right-shift  poll method for IO multiplexing:   1. Creating poll Objects:       p = select.poll   2. Register the following io:       p.register (s, Pollin | Pllerr)         not interested:          P.unregister (s)         event Category: & nbsp         pollin  pollout  pollerr  pollhup   POLLPRI      &NBS P     rlist          &NBSP;WList          xlist          break         Emergency handling  &nbsp ;  3. Monitoring io:       events = P.poll ()         Features: monitoring the IO events of interest       &NBS p; return value:            Return an IO event occurred    events is a list [(Fileno, Evnet), (), () ....]     Each Ready IO corresponds to a tuple (descriptor, ready event)            io map: {S.fileno ():s}   4. Handling IO Events & nbsp; local sockets:       functions:      data transfer between different programs for local files     Local socket transfer process:      1. Create a local socket object           SOCKFD = socket (Af_unix, sock_stream)       2. Bind a socket file, as If the file does not exist then it will be created automatically if there is an error          sockfd.bind (file)       3. Monitoring         nbsp;listen      4. Messaging         &NBSP;RECV send   multitasking programming:      The use of multiple cores of the computer to achieve simultaneous execution of multiple tasks       thus achieveThe purpose of the operation efficiency of the program       parallel:        Multiple computer cores are simultaneously working on multiple tasks,        Then multiple tasks are parallel relationships and nbsp     Concurrent:        running multiple tasks simultaneously, the kernel is constantly switching between multiple tasks,        Achieving the processing effect that multiple tasks will perform   & nbsp     There are concurrent relationships between tasks       Programs:        executables, which are static and only occupy disk       process: & nbsp       is a dynamic process   program running      &NBSP;CPU time slice:          If there is a process that occupies the CPU at this point, we call the process a CPU time slice           multiple process tasks or rotating CPU time slices to form the concurrency effect      process features:         process is the smallest unit of operating system allocated resources         Each process has its own independent running space (4 g of virtual memory space)       & nbsp The processes are independent of each other and do not affect the status of     process:        Tri-State:            ready State:  &NBSP ;               process with execution conditions, waiting for system to allocate processor resources into run state             run: &NB Sp                 process occupied CPU is running             Wait state:                  process temporarily does not have operating conditions, need to block wait          Five-state:          &NBSP ;   Add new and terminated states on a tri-state basis                new:            &N Bsp     Create a new program, get system resources process               End:          &NBS P       Process execution end, freeing the resource process  os module:    Determining if a file exists:       os.path.exists (file)     Delete files:       os.remove (file)        os.unlink (file)     Create process:       os.fork ()     get process id:       os.getpid ()     Get parent process id:       os.getppid ()     quit a process:       os.exit ()     & nbsp  sys.exit (exit hint)    sYs.exit () can exit      orphan process by capturing Systemexit exception:    When the parent process exits the child process, the child process becomes an orphan process     The orphan process is automatically processed by the system when the process is adopted   exited the zombie process:    When the child process takes precedence over the parent process exits, the parent process does not process the child process's exit status     It becomes a zombie process     Zombie process stuck PCB consumes memory resources   How to avoid zombie process generation:    1. Parent process exits     2. Parent process processes subprocess status   process zombie process:     & nbsp    pid,status = os.wait ():           wait blocking the exit of the waiting process subprocess in the parent process       &N Bsp     fear PID and exit status of returned subprocess        pid,status = Os.waitpid (pid,option):           waitpid in parent process block wait for processing subprocess exit             parameters:        &NBSP ;      pid   -1 means waiting for any sub-process to exit                    &NB Sp  >0 indicates that the subprocess waiting for the corresponding PID number exits option                       0 Blocking wait Wnohang represents non-blocking              Return of retired subprocess PID and exit status using level two subprocess:      Parent process Create child process wait process exit       Child process create next process and exit immediately       Level two sub-process becomes orphan process   handling specific work  multiprocessing module     process ()       Features:        Create process object       parameters:       target: Function object       &NB Sp;name to the process new name ()        args: Tuple used to give the target function location parameters        kwargs: The dictionary is used to pass the target function key value nbsp   START process:       p.start ()           Call binding function There are child processes running     waiting for the child process to exit:        p.join ([timeout detection])           do not use join to reclaim possible zombie processes after      Using multiprocessing to create a process child process also replicates all the memory space of the parent process     has its own independent space to execute the non-interfering sub-process also has its own PID specific resources     Using multiprocessing to create child processes, the general parent process feature is used only to create child processes     Reclaim child processes, return events to the child process to complete

Python network programming (weekly Summary1)

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.