Consider the past you shall know the future --day5
IP It's English Internet Protocol Abbreviation , intend “ A protocol for interconnection between networks ”, That is to say, the protocol designed for computer networks to communicate with each other . When multiple devices want to communicate ,ip The address must be unique .
IP Address = network address + The host address ,（ also called ： Network number and host number constitute ）
network number 、 It is necessary to determine the host number “ Subnet mask ”
Public network ip classification
- A class ： This kind IP The front of the address is “1000”（184.108.40.206-220.127.116.11）（ Default subnet mask ：255.0.0.0 or 0xFF000000）
- B class ： This kind IP The front of the address is “1100”（18.104.22.168-22.214.171.124）（ Default subnet mask ：255.255.0.0 or 0xFFFF0000）
- C class ： This kind IP The front of the address is “1110”（126.96.36.199-188.8.131.52）（ Subnet mask ：255.255.255.0 or 0xFFFFFF00）
- D class ： It's a multicast address . This kind IP The front of the address is “1110”, So the network number of the address is in 224~239 Between . Generally used for multicast users .
- E class ： It's a reserved address . This kind IP The front of the address is “1111”, So the network number of the address is in 240~255 Between .
Private address is not directly in Internet Internet applications , Go up Internet If you want to change it to a public address . private ip There are the following ：
- A:：10.0.0.0-10.255.255.255 namely 10.0.0.0/8
- B：172.16.0.0-172.31.255.255 namely 172.16.0.0/12
- C：192.168.0.0-192.168.255.255 namely 192.168.0.0/16
Subnet mask is used to judge any two computers ip Whether the address belongs to the same subnet is based on . The simplest way to understand it is that two computers have their own ip Address and subnet mask and After operation , The result is the same , It means that the two computers are on the same subnet , Can communicate directly .
It can also be written as ：192.168.1.1/24
24 Namely 1 The number of
Use only ip Address communication can only be accurate to a host , So the identifier that can distinguish different programs is added ： port .
Port usage 2 Bits to represent , The range is 0~25535.
There are two types of ports ：
- Known as port （Well Known Ports）
- The known port is a well-known port number , Range from 0 To 1023, among 80 Port allocation WWW service ,21 Port allocation FTP Service etc. .
- It is well known that port monitoring needs to have root jurisdiction .
- Dynamic port （Dynamic Ports）
- Dynamic ports range from 1024 To 65535. It's called dynamic ports , Because it doesn't always allocate certain services , It's dynamic allocation .
See more ：
- IP Address , Subnet mask , The default gateway ,DNS Server details
- computer network : IP Address , Subnet mask , Segment representation , The default gateway ,DNS Server details
iso Seven layers
socket For socket , It's an abstraction layer between the application layer and the transport layer , It is the TCP/IP Layer complex operations are abstracted into several simple interfaces to supply layer calls to realize process communication in the network .socket yes " open — read / Write — close " The realization of pattern .
TCP/IP Agreement is Internet The most basic agreement 、Internet The foundation of Internet , By the network layer IP Protocol and transport layer TCP The agreement consists of .
TCP An agreement is like a phone call , Yes “ hit - conversation - hang ” Three processes ,“ hit ”： It refers to the link between the client and the server （ Three handshakes ）;“ conversation ”： Communication between the two ends ;“ hang ”： The client or server initiates a disconnect request .
notes ：seq:"sequance" Serial number ;ack:"acknowledge" Confirmation no. ;SYN:"synchronize" Request synchronization flag ;;ACK:"acknowledge" Confirmation mark ";FIN："Finally" End mark .
stay python Easy to use TCP
Reference resources tcp cs Model ：
""" Server side """ import socket tcp_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # SOCK_STREAM yes tcp agreement # binding ip Address and listening port tcp_sock.bind(("", 8899)) # ip When the address is an empty string , It means the machine tcp_sock.listen(50) # Buffer size # Waiting for link new_sock, addr = tcp_sock.accept() recv_data = new_sock.recv(1024) # closed print(recv_data.decode()) new_sock.send(recv_data) # Hair # close new_sock.close() tcp_sock.close() """ client """ import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Connect s.connect(("127.0.0.1", 8899)) s.send(b"hello") data = s.recv(1024) print(data.decode()) s.close()
The simple example above can only handle one request , To process multiple requests at the same time , It can be realized in the following way ：
Multi line （ Into the ） cheng
""" Server side """ import socket from concurrent.futures import ThreadPoolExecutor def process_client(client, addr): """ Processed Links , Send and receive """ try: while True: recv_data = client.recv(1024) # closed print(recv_data.decode()) client.send(recv_data) # Hair finally: # close client.close() def main(): tcp_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tcp_sock.bind(("", 8899)) # ip When the address is an empty string , It means the machine tcp_sock.listen(50) # Buffer size # Waiting for link try: while True: new_sock, addr = tcp_sock.accept() with ThreadPoolExecutor(12) as t: t.submit(process_client, new_sock, addr) # If it's multi process , At this point, we should add new_socke.close() # Because with multiprocessing , The resource will be copied to another process finally: tcp_sock.close() if __name__ == '__main__': main() """ client """ import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Connect s.connect(("127.0.0.1", 8899)) while True: data = input(">>>") if not data: continue s.send(data.encode()) print(s.recv(1024).decode()) s.close()
python Except for socket Library provides socket Support outside , also socketserver Provide server centric classes , It can simplify the development of network server .
Use steps ：
1、 Create an inheritance socketserver.BaseRequestHandler Class
2、 Class must override one named handler Methods
3、 Instantiate a server class , The address and request handler class passed in to the server
4、 call serve_forever() Event loop monitoring
Be careful ： Class self.request stay TCP Is a linked socket object ;UDP When is (data, udp socket object ) Need help self.client_address Sending data
""" Server side """ import socketserver class MyServer(socketserver.BaseRequestHandler): def handle(self) -> None: print(self.client_address) # Address while True: recv_data = self.request.recv(1024) # closed # print(recv_data.decode()) self.request.send(recv_data) # Hair def main(): s = socketserver.ThreadingTCPServer(("", 8899), MyServer) s.serve_forever() if __name__ == '__main__': main()
See more ：socketserver How to use the module
see day4 The last example of
No connection 、 ordinary 、 Packet oriented transport layer protocol .
""" Server side """ import socket udp_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) udp_sock.bind(("", 8899)) while True: data, addr = udp_sock.recvfrom(1024) print(data) udp_sock.sendto(data, addr) """ client """ import socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) data = input(">>>") # Send a message , data +ip port s.sendto(data.encode(), ("127.0.0.1", 8899)) print(s.recvfrom(1024)) s.close()
udp radio broadcast
The main points of ：
- The sending address is
- Set up socket Options
""" udp radio broadcast Intralocal , Just monitor 8899 port , You can get messages """ import socket udp_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Address sent ip_port = ("<broadcast>", 8899) # modify socket Options , Fixed format udp_sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) udp_sock.sendto(b"test", ip_port) while True: recv_data = udp_sock.recvfrom(1024) print(recv_data)
What is? http agreement
http Agreement is Hypertext Transfer Protocol --（ Hypertext transfer protocol ） Abbreviation , A lot of communication protocols are used in the field of Internet .
HTTP It's an application layer protocol , Consists of a request and a response , Is a standard client server model .HTTP Is a stateless protocol .
HTTP The agreement is based on TCP An application over the protocol .
1） stay HTTP 1.0 in , Each request from the client requires a separate connection , After processing this request , Just release the connection automatically .
2） stay HTTP 1.1 in , Can be in Processing multiple requests in a single connection , And multiple requests can overlap , There is no need to wait for one request to finish before sending the next one .
http The process of
- Server monitoring 80 port , Wait for the request
- client （ It's usually a browser ） Initiate request
- Server processing request , Return the data
- The client or server is disconnected
URI and URL
URI Identify an Internet resource with a string , and URL Indicates the location of the resource . so URL yes URI Subset .
URI To use... With all the necessary information URI、 absolute URL And relative URL.
relative URL It's basically from the browser URI To deal with the URL, Let's take a look at URI The format of ：
POST /test/index.html HTTP/1.1 Accept: */* Accept-Language: zh-cn host: localhost Content-Type: application/x-www-form-urlencoded Content-Length: 12 Connection:close sn=123&n=asa
HTTP/1.1 200 OK Server:Apache Tomcat/5.0.12 Date:Mon,6Oct2003 13:23:42 GMT Content-Length:112 <html> <head> <title>HTTP Response example <title> </head> <body> Hello HTTP! </body> </html>
Server will URL The located resources are placed in the data part of the response message , Send back to the client
？stay URL At the end of the passage , Use... Between multiple parameters
&separate , Such as
/index.html?id=10&op=bind, The length of the transfer parameter is limited , And Not suitable for transmitting private data .
POST Method encapsulates the request parameters in HTTP Request data , By name / The form of value appears , It can transmit a lot of data . For example, where is the request message .
image GET, It's just that the server receives HEAD Only the response header is returned after the request , Instead of sending the response content . For viewing the status of a page .
Can be used to transfer files , It's like FTP The protocol file upload is the same , It is required to include the file content in the body of the request message , Then save to request url Designated location . because put There is no verification mechanism for the method , Anyone can upload files , There are security issues .
Used to delete files , Is with the put The opposite way ,delete Method on request url Delete the specified resource . Its essence and put Method without verification mechanism .
All the way ：
The status code consists of three digits , The first number defines the category of response , And there are five possible values .
1xx： instructions -- Indicates that the request has been received , To continue processing .
2xx： success -- Indicates that the request was received successfully 、 understand 、 Accept .
3xx： Redirect -- Further action must be taken to complete the request .
4xx： Client error -- The request has a syntax error or the request cannot be implemented .
5xx： Server-side error -- The server could not fulfill the legitimate request .
Common status code 、 The description of the state is as follows .
200 OK： Client request successful .
400 Bad Request： Client request has syntax error , Not understood by the server .
401 Unauthorized： Request not authorized , The status code must be equal to WWW-Authenticate Header fields are used together .
403 Forbidden： The server receives the request , But refused to provide service .
404 Not Found： The requested resource does not exist , for instance ： I typed the wrong one URL.
500 Internal Server Error： An unexpected error occurred on the server .
503 Server Unavailable： The server is currently unable to process the client's request , It may return to normal after some time , for instance ：HTTP/1.1 200 OK（CRLF）.
Cookie Is used to maintain the server session state , Usually written by the server , In subsequent requests , A piece of text for the server to read .
cookie Technology by writing in the request and the corresponding message cookie Information to control the state of the client .cookie According to one of the corresponding messages sent from the server, it is called
set-cookie First field information of , Notify the client to save cookie. The next time the client sends a request to the server , The client will automatically add cookie Send it when it's worth
more ： Elaborate Cookie
Session Is a mechanism used by the server to record the state of the client , Use the upper comparison Cookie It's simpler , Correspondingly, it also increases the storage pressure of the server .
Session Object is created the first time the client requests the server .
more ：cookie and session The detailed explanation and difference of
See this article for details ：HTTPS Popular science literacy post
【 To be completed 】