Python-based socket programming
A TCP/IP five layer model
In each layer of the work of different devices, such as our common switches work in the data link layer, the general router is working in the network layer.
The protocols that are implemented at each level are also different, that is, the services at each level are different. Lists the main protocols for each layer.
Each layer function
Note: What level of ARP and RAPR two belong to exactly?
Because the IP protocol uses the ARP protocol, the ARP protocol is often zoned to the network layer, but the ARP protocol is designed to resolve the MAC address used at the data link layer from the IP address used by the network layer, so some places also divide the ARP protocol into the data link layer, but in general, We still divide the ARP and RARP protocols into the network layer.
There is no clear line, not too tangled.
Two. Socekt Layer
A socket is an intermediate software abstraction layer that the application layer communicates with the TCP/IP protocol family, which is a set of interfaces. In design mode, the socket is actually a façade mode, it is the complex TCP/IP protocol family hidden behind the socket interface, for the user, a set of simple interface is all, let the socket to organize data to meet the specified protocol.
So, we do not need to understand the TCP/UDP protocol, the socket has been packaged for us, we only need to follow the socket rules to program, write the program is naturally follow the TCP/UDP standard.
Some people also say that the socket is used to identify the location of a host in the Internet, and port is used to identify an application on this machine, the IP address is configured on the network card, and the port is the application Ip+port,ip, The IP-to-port binding identifies an application that is unique to the Internet.
The PID of the program is the identification of different processes or threads on the same machine.
So where the hell is it? Or use a diagram to speak, at a glance.
Three socket 3.1 socket family
Socket family name based on file type:AF_UNIX
unixall files, file-based sockets call the underlying filesystem to fetch data, and two socket processes run on the same machine and can communicate indirectly by accessing the same file system.
Socket family name based on network type:AF_INET
There are also AF_INET6 other address families that are used, ipv6 but they are either used only on a platform, or have been discarded, or are rarely used, or are not implemented at all, and AF_INET are the most widely used of all address families, Python supports a variety of address families, but since we only care about network programming, most of the time I use only AF_INET .
3.2 Workflow for sockets
Start with the server side. The server-side initializes the socket, then binds to the port (BIND), listens to the port (listen), calls the Accept block, waits for the client to connect. At this point if a client initializes a socket and then connects to the server (connect), the client-server connection is established if the connection is successful. The client sends the data request, the server receives the request and processes the request, then sends the response data to the client, the client reads the data, closes the connection, and ends the interaction at the end.
Four socket () module function usage
1 ImportSocket2Socket.socket (socket_family,socket_type,protocal=0)3 socket_family can be Af_unix or af_inet. Socket_type can be sock_stream or sock_dgram. Protocol is generally not filled, the default value is 0. 4 5Get tcp/IP Sockets6Tcpsock =Socket.socket (socket.af_inet, socket. SOCK_STREAM)7 8Get udp/IP Sockets9Udpsock =Socket.socket (socket.af_inet, socket. SOCK_DGRAM)Ten OneBecause there are too many properties in the socket module. We made an exceptional use of it here.'From module Import *'Statement. Use'From socket Import *', we took all the attributes from the socket module into our namespace, which greatly shortened our code. AFor example Tcpsock = socket (af_inet, SOCK_STREAM)
Service-Side socket functions
S.bind () binding (host, port number) to socket
S.listen () Start TCP listener
s.accept () passively accepts a TCP client connection, (blocking) waits for a connection to arrive
Client socket functions
S.connect () Active initialization of TCP server connections
Extended version of the S.CONNECT_EX () 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 () sends TCP data (send data is lost when the amount of data to be sent is greater than the remaining space in the cache)
S.sendall () sends the full TCP data (essentially a cyclic call Send,sendall the data is not lost when the amount of data to be sent is greater than the remaining space in the buffer, and the call to send is sent until it is finished)
S.recvfrom () receiving 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 () sets the parameters of the specified socket
s.close () Close socket
Lock-oriented socket method
s.setblocking () sets the blocking and non-blocking mode for sockets
S.settimeout () sets the timeout period for blocking socket operations
s.gettimeout () Gets the timeout period for blocking socket operations
functions for file-oriented sockets
S.fileno () The file descriptor of the socket
S.makefile () Create a file associated with the socket
Five TCP-based sockets
TCP is link-based, you must start the server, and then start the client to link the server
TCP Service Side
1SS = Socket ()#Create a server socket2Ss.bind ()#bind an address to a socket3Ss.listen ()#Monitoring Links4Inf_loop:#Server Infinite loop5cs = ss.accept ()#Accept Client Links6Comm_loop:#Communication Cycle7CS.RECV ()/cs.send ()#dialog (receive and send)8Cs.close ()#close the client socket9Ss.close ()#to turn off server sockets (optional)
TCP Client
1 cs = socket () # Create client socket 2 cs.connect () # try to connect to the server 3 comm_loop: # communication loop 4 cs.send ()/cs.recv () # Dialog (send/Receive)5 cs.close () # close client sockets
The socket communication process is similar to the call process, and we use the phone as an example to achieve the lowest-level socket communication
ImportSocketphone=socket.socket (Socket.af_inet,socket. SOCK_STREAM)#buy a cell phonePhone.bind (('127.0.0.1', 8080))#Binding Mobile CardPhone.listen (5)#BootPrint('starting ...') conn,client_addr=phone.accept ()#and so on the phone (link, the client's IP and the port consisting of tuples)Print(CONN,CLIENT_ADDR)#collect, send a messageDATA=CONN.RECV (1024)Print('client data: <%s>'%data) Conn.send (Data.upper ())Service Side
ImportSocketphone=socket.socket (Socket.af_inet,socket. SOCK_STREAM)#buy a cell phonePhone.connect (('127.0.0.1', 8080))#Binding Mobile Card#send and receive messagesPhone.send ('Hello'. Encode ('Utf-8')) Data=PHONE.RECV (1024)Print('Server Back res:<%s>'%data) Phone.close ()Client
Plus link loops and communication loops
ImportSocketphone=socket.socket (Socket.af_inet,socket. SOCK_STREAM)#buy a cell phonePhone.setsockopt (socket. Sol_socket,socket. so_reuseaddr,1)#That 's it, in front of BIND plusPhone.bind (('192.168.20.60', 8081))#Binding Mobile CardPhone.listen (5)#BootPrint('starting ...') whileTrue:#Link LoopsConn,client_addr=phone.accept ()#and so on the phone (link, the client's IP and the port consisting of tuples) Print('-------->', CONN,CLIENT_ADDR)#collect, send a message whileTrue:#Communication Cycle Try:#Add the reason is because in the connection cycle, if the connection at this time the client disconnects, the Conn connection disconnects, receive data error, the program will be interrupted, the other customer service information will not come inDATA=CONN.RECV (1024) #if not data:break #针对linux Print('client data: <%s>'%data) Conn.send (Data.upper ())exceptException: Breakconn.close ()#Hang up the phonePhone.close ()#turn off the machineimproved version of the service side
ImportSocketphone=socket.socket (Socket.af_inet,socket. SOCK_STREAM)#buy a cell phonePhone.connect (('192.168.20.60', 8081))#Binding Mobile Card#send and receive messages whiletrue:msg=input ('>>:'). Strip ()if notMsgContinue #If this is not the case, when the input is empty, it will be trapped in a dead loop when the server receives it.Phone.send (Msg.encode ('Utf-8')) Data=PHONE.RECV (1024) Print('Server Back res:<%s>'%data) Phone.close ()Improved client
Python-based socket programming