I. Introduction to Sockets
1. Introduction to Sockets
<1> networked applications must create sockets before any communication can begin, and there is no way to communicate without it.
At the beginning of <2>, sockets are designed for communication between multiple applications on the same host, which is also called interprocess communication, or IPC.
There are two types of <3> sockets, based on file type and network based type.
<4>af_unix represents "Address family: UNIX" –> file-based.
Af_inet represents the "Address family: Internet" –> network based.
<5>python only supports Af_inet, Af_unix and Af_netlink families.
2. Socket address: Host and port
Sockets are the lowest structure of communication. An Internet address is made up of the hosts and ports necessary for network traffic.
3. Connection-oriented and no connection
Regardless of which address family is used, there are only two types of sockets: connection-oriented sockets and connectionless sockets
<1> Connection-oriented sockets
I. must establish a connection before the communication, the connection-oriented mode of communication provides a sequential, reliable, no duplication of data transmission.
II. The primary protocol for achieving such a connection is TCP (Control Protocol), in order to create a TCP socket, you must specify the type of socket as sock_stream when you create it.
<2> Sockets with no connection
I. Communication is possible without connection, the order of data arrival, reliability and repeatability of data cannot be guaranteed.
II. The primary protocol for achieving such a connection is UDP (User Datagram Protocol), and to create a UDP socket you must specify the socket type as SOCK_DGRAM when you create it.
Two. Network programming in Python
Mainly using the socket module, the socket () function in the module is used to create sockets. Sockets provide a series of functions to support network traffic based on sockets.
1.socket () module function
Use the Socket.socket () function to create sockets, Syntax:
Sockete (socket_family,socket_type,protocol=0)
Explain:
Socket_family can be Af_unix or af_inet;socket_type can be sock_stream or sock_dgram;protocol generally do not fill, the default value is 0.
<1> create a socket for TCP/IP
Tcpsock=socket.socket (Socket.af_inet,socket. SOCK_STREAM)
<2> Creating a UDP/IP socket
Udpsock=sock.socket (Socket.af_inet,socket. SOCK_DGRAM)
2. Socket Object method
The main methods of socket s are described in the picture: