Python Socket network programming, pythonsocket
What is network?
A network is composed of nodes and connections, indicating many objects and their intercommunication. In mathematics, the network is a type of graph, which is generally regarded as a weighted graph. In addition to mathematical definitions, the network also has a specific physical meaning, that is, the network is a model abstracted from some practical problems of the same type. In the computer field, the network is a virtual platform for information transmission, receiving, and sharing. It connects the information of various points, faces, and bodies to achieve the sharing of these resources. Network is the most important invention in the history of human development, improving the development of science and technology and human society.
Three elements of network communication
- IP address
- Used to represent an independent host
- The Special IP address 127.0.0.1 or localhost (indicating the local loopback address, reserved address, etc.) can be used for local testing.
- Port Number
- To send data to the application specified by the peer, network applications are identified by numbers to identify these applications. These numbers are called ports for convenience.
- Transmission Protocol
- TCP: Transmission Control Protocol
- Connection-oriented: establish a connection before transmission
- Massive Data Transmission During connection
- The three-way handshake is a secure and reliable connection.
- Low transmission rate and efficiency
- UDP protocol: User transmission protocol
- Connection-free: You can transmit data without establishing a connection during transmission.
- The size of each data transmission is limited to 64 KB
- Unreliable Transmission
- Fast transmission rate and high efficiency
SOCKET network programming
For example, simply implementing a WEB Applet
Import socketdef handle_request (client): buf = client. recv (1024) client. send (bytes ("HTTP/1.1 200 OK \ r \ n", 'utf8') client. send (bytes ("Hello, World", 'utf8') def main (): sock = socket. socket (socket. AF_INET, socket. SOCK_STREAM) sock. bind ('localhost', 8080) sock. listen (5) while True: connection, address = sock. accept () handle_request (connection) connection. close () if _ name _ = '_ main _': main ()WEB applets
Python provides two levels of network services for access:
- Low-level network services support basic Sockets. It provides the standard BSD Sockets API and can access all the methods of Socket interfaces of the underlying operating system.
- SocketServer, a high-level network service module, provides a server center class to simplify the development of network servers.
What is socket?
Socket, also known as "Socket", usually uses "Socket" to send a request to or respond to a network request, so that processes on a host or computer can communicate with each other.
Socket () function:
socket.socket([family[, type[, proto]]])
Parameters
- Family: the socket family can make AF_UNIX or AF_INET
- Type: the socket type can be divided into connection-oriented or non-connection-oriented
SOCK_STREAMOrSOCK_DGRAM
- Protocol: Generally, the default value is 0.
Communication Process
1 ####### server ########## 2 3 import socket 4 5 sk = socket. socket () 6 address = ('2017. 0.0.1 ', 8000) 7 sk. bind (address) 8 sk. listen (3) 9 10 while True: 11 conn, addr = sk. accept () 12 while True: 13 try: 14 data = conn. recv (1024) 15 print (str (data, 'utf8') 16 if not data: 17 break18 indium = input (">>>") 19 conn. send (bytes (indium, 'utf8') 20 bytes t Exception: 21 break22 23 conn. close () 24 25 ########## Client ########### 26 import socket27 28 sk = socket. socket () 29 address = ('2017. 0.0.1 ', 8000) 30 sk. connect (address) 31 while True: 32 indium = input (">>>") 33 if indium = "exit": 34 break35 sk. send (bytes (indium, 'utf8') 36 data = sk. recv (1024) 37 print (str (data, 'utf8') 38 sk. close ()Simple built-in QQ chat Socket Method
S. bind (): bind the address (host, port) to the socket. In AF_INET, the address is expressed in the form of a tuples (host, port. S. listen () starts TCP listening. Backlog specifies the maximum number of connections that the operating system can suspend before a connection is denied. This value must be at least 1, and most applications can be set to 5. S. accept () passively accepts TCP client connections and waits for the connection to arrive.
The client socket s. connect () Actively initializes the TCP server connection ,. Generally, the format of address is tuples (hostname, port). If a connection error occurs, the socket. error is returned. Extended version of s. connect_ex () connect () function. An error code is returned when an error occurs, instead of throwing an exception.
The common socket function s. recv () receives TCP data, and the data is returned as a string. The bufsize specifies the maximum data volume to receive. Flag provides other information about messages, which can be ignored. S. send () sends TCP data and sends the data in string to the connected socket. The returned value is the number of bytes to be sent, which may be smaller than the size of the string. S. sendall () completely sends TCP data, and completely sends TCP data. Send data in string to the connected socket, but try to send all data before returning. If None is returned successfully, an exception is thrown. S. recvform () receives UDP data, which is similar to recv (), but returns (data, address ). Data is the string containing the received data, and address is the socket address for sending data. S. sendto () sends UDP data and sends the data to the socket. The address is a tuples in the form of (ipaddr, port) and specifies the remote address. The returned value is the number of bytes sent. S. close () closes socket s. getpeername () and returns the remote address of the connection socket. The returned value is usually a tuples (ipaddr, port ). S. getsockname () returns the address of the socket itself. It is usually a tuples (ipaddr, port) s. setsockopt (level, optname, value) to set the value of the given socket option. S. getsockopt (level, optname [. buflen]) returns the value of the socket option. S. settimeout (timeout) sets the superperiod of socket operations. timeout is a floating point number, measured in seconds. If the value is None, there is no superperiod. Generally, it should be set when the socket is just created during the superperiod, because they may be used for connection operations (such as connect () s. gettimeout () returns the value of the current superperiod in seconds. If no superperiod is set, None is returned. S. fileno () returns the file descriptor of the socket. S. setblocking (flag) if the flag is 0, the socket is set to non-blocking mode; otherwise, the socket is set to blocking mode (default ). In non-blocking mode, if no data is found when recv () is called, or the send () call cannot send data immediately, a socket. error exception occurs. S. makefile () creates a file related to the socket
Instance
######### Server ########## import socketimport subprocesssk = socket. socket () address = ('2017. 0.0.1 ', 8000) sk. bind (address) sk. listen (3) while True: conn, addr = sk. accept () while True: try: data = conn. recv (1024) failed t Exception: break if not data: break # print (str (data, 'utf8') # data = str (data, 'utf8 ') # decode the same as decode obj = subprocess. popen (data. decode ('utf8'), shell = True, stdout = subprocess. PIPE) ssh _ Result = obj. stdout. read () result_len = bytes (str (len (ssh_result), 'utf8') conn. send (result_len) conn. send (ssh_result) conn. close () ######### Client ######### import socketsk = socket. socket () address = ('2017. 0.0.1 ', 8000) sk. connect (address) while True: indium = input (">>>") if indium = "exit": break sk. send (bytes (indium, 'utf8') result_len = int (str (sk. recv (1024), 'utf8') print (result_len) data = bytes () whil E len (data )! = Result_len: recv = sk. recv (1024) data + = recv print (str (data, 'gbk') sk. close ()Simple access to SSH function File Upload import socketimport ossk = socket. socket () address = ('2017. 0.0.1 ', 8000) sk. bind (address) sk. listen (3) BASE_DIR = OS. path. dirname (OS. path. abspath (_ file _) while True: conn, addr = sk. accept () while True: data = conn. recv (1024) cmd, file_name, file_size = str (data, 'utf8 '). split ('|') path = OS. path. join (BASE_DIR, 'model', file_name) file_size = int (file_size) f = open (path, 'AB') has_recv = 0 while has_recv! = File_size: data = conn. recv (1024) f. write (data) has_recv + = len (data) f. close ()Serverimport socketimport ossk = socket. socket () address = ('2017. 0.0.1 ', 8000) sk. connect (address) BASE_DIR = OS. path. dirname (OS. path. abspath (_ file _) while True: indium = input (">>>> "). strip () path = OS. path. join (BASE_DIR, indium) file_name = OS. path. basename (path) file_size = OS. stat (path ). st_size file_info = 'Post | % s | % s' % (file_name, file_size) sk. sendall (bytes (file_info, 'utf8') f = open (path, 'rb ') Has_sent = 0 while has_sent! = File_size: data = f. read (1024) sk. sendall (data) has_sent + = len (data) f. close () print ("uploaded successfully ")Client socketserver
The socketserver module simplifies the tasks of network programming service programs, And the SocketServer module is also the basis of many server frameworks in the Python standard library.
The best way to learn about it is to browse its source code.
First, let's take a look at how to use
Import socketserverclass MyServer (socketserver. baseRequestHandler): def handle (self): print ("server startup") while True: conn = self. request while True: data = conn. recv (1024) print (str (data, 'utf8') indium = input (">>>>") conn. sendall (bytes (indium, 'utf8') conn. close () if _ name _ = '_ main _': server = socketserver. threadingTCPServer ('2017. 0.0.1 ', 8080), MyServer) server. serve_forever ()Serverimport socketsk = socket. socket () address = ('2017. 0.0.1 ', 8080) sk. connect (address) print ("client startup") while True: indium = input (">>>>") sk. sendall (bytes (indium, 'utf8') if indium = "q": break data = sk. recv (1024) print (str (data, 'utf8') sk. close ()Client
This Code allows the server to chat with multiple clients at the same time.
Before looking at the source code, we should first make it clear that it divides several classes and the functions of each class.
There are five classes in an inheritance dives, four of which represent
Synchronous servers of four types:
The following will not be detailed in detail. If you want to know more thoroughly, read the source code again.