Python Learning notes----network programming

Source: Internet
Author: User

Network Programming concepts that need to be known for network programming

1. Network architecture is the use of these different media connected by different devices and network systems in different application environments to achieve interoperability, and meet a variety of business needs of a binder. The network architecture solves the coprime problem color is the stratification method.

Network (OSI) 7-tier model:

Application Layer---> provides network communication services for Applications

Presentation Layer---> Data representation

Session Layer---> Inter-Host communication (two application processes)

Transport Layer---> End-to-end connection, isolating the network's upper and lower protocols, making the network application irrelevant to the lower layer protocol

Network Layer---> Find the optimal path, forward the packet

Data Link Layer---> Error-free link connection

Physical Layer---> binary transfer

2. Ports

is an abstract software structure that includes some data structures and I/O buffers. Related to the agreement.

3. The socket exists in the communication area. The communication area, also known as the address family, is an abstract concept that is primarily used to synthesize the common features of processes that communicate through sockets.

In order to ensure the correctness of data, it is necessary to make network byte sequence in network protocol, and adopt unified network byte order.

Three elements of network communication:

IP address: Used to represent the host (IP address = network id+ host ID)

Port number: The logical port used to identify the process

Transport protocol: TCP UDP

The process of network communication is an ongoing process of encapsulation and parsing.

A socket is a bridge between an application and a network driver, and the socket is created in the application to establish a relationship with the driver through a binding operation.

Sockets

Sockets are objects that provide the current portable standard for network application providers on a specific network protocol (such as TCP/IP,ICMP/IP,UDP/IP, etc.) suite pair. They allow the program to accept and make connections, such as sending and receiving data. In order to establish a communication channel, it is extremely important for each endpoint of a network communication to have a socket object.

Sockets are part of the BSD Unix system core, and they are also adopted by many other Unix-like operating systems including Linux. Many non-BSD Unix systems, such as the Ms-dos,windows,os/2,mac OS and most host environments, provide support for sockets in the form of libraries.

The three most popular types of sockets are: Stream,datagram and raw. Stream and datagram sockets can interface directly with the TCP protocol, while the raw sockets interface to the IP protocol. However, sockets are not limited to TCP/IP.

Socket Module------- socket () module

The socket module is a very simple object-based interface that provides access to the low-level BSD socket style network. Use this module to implement client and server sockets. To build a simple server with TCP and streaming sockets in Python, you need to use the socket module. Using the functions and class definitions contained in the module, you can generate programs that communicate over the network. to build a simple server with TCP and streaming sockets in Python, you need to use the socket module. Using the functions and class definitions contained in the module, you can generate programs that communicate over the network.  

   

Soc

SOCKET Built-in method
Function Describe
Server-side socket functions
S.bind () Bind address (host, port number pair) to socket
S.listen () Start TCP snooping
S.accept () Passive acceptance of TCP client connections, (blocking) waiting for a connection to arrive
Client socket functions
S.connect () Active initialization of TCP server connections
S.CONNECT_EX () Extended version of the Connect () function, which returns an error code instead of throwing an exception when an error occurs
Socket functions for public use
S.RECV () Receiving TCP Data
S.send () Sending TCP data
S.sendall () Complete sending of TCP data
S.recvfrom () Receive UDP data
S.sendto () Send UDP data
S.getpeername () The address of the remote that is connected to the current socket
S.getsockname () Address of the current socket
S.getsockopt () Returns the parameters of the specified socket
S.setsockopt () To set parameters for a specified socket
S.close () Close socket
module-oriented socket functions
S.setblocking () To set the blocking and non-blocking mode for sockets
S.settimeout () A To set the timeout period for blocking socket operations
S.gettimeout () A Get the timeout for blocking socket operations
Functions for file-oriented sockets
S.fileno () File descriptor for sockets
S.makefile () Create a file that relates to the socket
A. New functions added to Python version 2.3

Establishing a server connection requires six steps:

  1. Create the Socket object. Call the socket constructor.

Socket=socket.socket (Familly,type)

The value of family can be Af_unix (UNIX domain for interprocess communication on the same machine) or af_inet (TCP and UDP for IPV4 Protocol), as for the type parameter, SOCK_STREAM (stream socket), or Sock_ Dgram (data message socket), SOCK_RAW (RAW socket).

  2. the socket is bound (assigned) to the specified address, socket.bind (address)

Address must be a two-element tuple, ((Host,port)), host name or IP address + port number. If the port number is being used or reserved, or if the hostname or IP address is wrong, a Socke.error exception is thrown.

  3. after binding, the socket must be prepared to accept the connection request.

Socket.listen (Backlog)

The backlog specifies the maximum number of connections, at least 1, after the connection request is received, the requests must be queued, and if the queue is full, the request is rejected.

  4. The server socket waits for the client to request a connection through the socket's Accept method:

Connection,address=socket.accept ()

When the Accept method is called, the socket enters the ' waiting ' (or blocked) state. When a client requests a connection, the method establishes the connection and returns the server. The Accept method returns a tuple that contains two elements, such as (connection,address). The first element (connection) is the new socket object through which the server communicates with the customer, and the second element (address) is the customer's Internet address.

  5. during the processing phase, the server and the customer communicate via the Send and Recv methods (transfer data). The server calls send and sends a message to the customer in string form. The Send method returns the number of characters that have been sent. The server uses the Recv method to accept information from the customer. When calling recv, you must specify an integer to control the maximum amount of data that is accepted by this call. The Recv method enters the ' Blocket ' state when the data is accepted, and finally returns a string that represents the received data. If the amount sent exceeds the allowable recv, the data is truncated. The excess data will be buffered on the receiving end. When you call recv later, the extra data is removed from the buffer.

  6. at the end of the transfer, the server calls the socket's Close method to close the connection.

Establishing a simple client connection requires 4 steps.

1th step, create a socket to connect to the server Socket=socket.socket (Family,type)

2nd step, connect to Server Socket.connect ((host,port)) using the socket's Connect method

3rd, the client and server communicate via the Send and recv methods.

At the end of the 4th step, the customer closes the connection by calling the Close method of the socket.

ImportSocketsk=socket.socket () address= ('127.0.0.1', 8000) Sk.bind (address) Sk.listen (2)Print("......") whileTrue:conn, addr=sk.accept ()Print(addr) whileTrue:Try: Date= CONN.RECV (1024)        exceptException: Break        if  notDate Break        Print(Str (DATE,"UTF8")) InP= Input (">>>>:") conn.send (bytes (INP,"UTF8"))#conn, addr = sk.accept ()#While True:#date = Conn.recv (1024x768)#If not date:#conn, addr = sk.accept ()#Continue#Print (str (date, "UTF8"))#INP = input (">>>>:")#conn.send (bytes (INP, "UTF8"))#conn.close ()Conn.close ()
Service Side
ImportSocketsk=socket.socket () address= ("127.0.0.1", 8000) Sk.connect (address) whileTRUE:INP= Input (">>>>:")    ifINP = ="Q":         Breaksk.send (Bytes (INP,"UTF8")) Date= SK.RECV (1024)    Print(Str (DATE,"UTF8") ) Sk.close ()
Client

Simple analog QQ Conversation (socket module )

ImportSocket,subprocesssk=socket.socket () address= ('0.0.0.0', 8000) Sk.bind (address) Sk.listen (2)Print("......") whileTrue:conn, addr=sk.accept ()Print(addr) whileTrue:Try: Date= CONN.RECV (1024)        exceptException: Break        if  notDate Break        Print(Str (DATE,"UTF8")) obj= subprocess. Popen (str (DATE,"UTF8"), shell=true,stdout=subprocess. PIPE) Cmd_result=obj.stdout.read () Result_len=str (len (cmd_result))Print(result_len) conn.send (bytes (Result_len,"UTF8") ) conn.send (Cmd_result) conn.close ()
Server
ImportSocketsk=socket.socket () address= ("127.0.0.1", 8000) Sk.connect (address) whileTRUE:INP= Input (">>>>:")    ifINP = ="Q":         Breaksk.send (Bytes (INP,"UTF8")) Result_len= Int (str (SK.RECV (1024),"UTF8"))    Print(result_len) Date=bytes () whileLen (date)! =Result_len:da= SK.RECV (1024) Date+=daPrint(Str (DATE,"GBK") ) Sk.close ()
Client

Simple FTP upload image

ImportsubprocessImportSocketImportOssk=Socket.socket ()Print(SK) Address=('127.0.0.1', 8000) Sk.bind (address) Sk.listen (3)Print('Waiting ...') Base_dir=os.path.dirname (Os.path.abspath (__file__)) while1: conn, addr=sk.accept () while1: Data=CONN.RECV (1024) Cmd,filename,filesize=STR (data,'UTF8'). Split ('|') path=os.path.join (Base_dir,'Tupian', filename) filesize=Int (filesize) F=open (Path,'AB') has_receive=0 whilehas_receive!=Filesize:data=CONN.RECV (1024) f.write (data) has_receive+=len (data) f.close ()
Server
ImportSocketImportOssk=socket.socket () address=('127.0.0.1', 8000) Sk.connect (address) Base_dir=os.path.dirname (Os.path.abspath (__file__)) whileTRUE:INP=input ('>>>'). Strip ()#Post|11.pngCmd,path=inp.split ('|') path=os.path.join (base_dir,path) filename=os.path.basename (path) file_size=os.stat (path). St_size File_info='post|%s|%s'%(filename,file_size) sk.sendall (bytes (File_info,'UTF8')) F=open (Path,'RB') Has_sent=0 whilehas_sent!=File_size:data=f.read (1024) Sk.sendall (data) has_sent+=len (data) f.close ()Print('Upload Successful')
Client

Python Learning notes----network programming

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.