当前位置:网站首页>Socket communication principle

Socket communication principle

2022-06-25 11:04:00 Jacob_ Always

Socket The location of :
 Insert picture description here
Socket What is it? :
Socket Is the application layer and TCP/IP Intermediate software abstraction layer for protocol family communication , It's a set of interfaces . In design mode ,Socket It's a facade pattern , It's complicated TCP/IP The protocol family is hidden in socket The back of the interface , For users , A simple set of interfaces is all , Give Way socket To organize data , To comply with the specified protocol .

How to use :
Our predecessors have done a lot for us , Communication between networks is much simpler , But there is still a lot of work to be done . I heard it before socket Programming , I think it is a relatively advanced programming knowledge , But just find out socket How programming works , The veil of mystery is lifted .
A scene in life . You have to call a friend , Dial first , A friend picks up the phone when he hears it , This is the connection between you and your friends , And you can talk . When the communication is over , Hang up and end the conversation . Scenes in life explain how this works , Maybe TCP/IP The agreement clan is born in life .
 Insert picture description here
Let's start with the server . The server is initialized first socket, And then bind to the port (bind), Listen to the port (listen), call accept Blocking , Wait for the client to connect . At this time, if there is a client initializing a socket, And then connect to the server (connect), If the connection is successful , At this time, the connection between the client and the server is established . Client sends data request , The server accepts the request and processes it , Then send the response data to the client , Client reads data , Finally, close the connection , An interaction ends .

1. How processes communicate with each other in the network ?
Local process communication (IPC) There are many ways , But it can be summed up as follows 4 class :
: The messaging ( The Conduit 、FIFO、 Message queue )
: Sync ( The mutex 、 Condition variables, 、 Read-write lock 、 File and write record lock 、 Semaphore )
: Shared memory ( Anonymous and named )
: Remote procedure call (Solaris The door and Sun RPC)

We are going to talk about how processes in the network communicate with each other , The first problem to be solved is how to uniquely identify a process , Otherwise, communication is impossible . It can be done locally through processes PID To uniquely identify a process , But it doesn't work on the Internet . Actually TCP/IP The protocol family has solved this problem for us , Network layer “ip Address ” Can uniquely identify hosts in the network , And the transport layer “ agreement + port ” Can uniquely identify applications in the host ( process ). This uses triples (ip Address 、 agreement 、 port ) You can identify the process of the network , The process communication in the network can use this flag to interact with other processes .

Use TCP/IP The application program of the protocol usually uses the application programming interface :UNIX BSD Socket (socket) and UNIX System V Of TLI( Eliminated ), To achieve communication between network processes . For now , Almost all applications use socket, And now it's the Internet age , Process communication is ubiquitous in the network , So “ Everything is socket”.

2. What is? socket:
Socket Come of Unix, and Unix/Linux One of the basic philosophies is “ Everything is a document ”, Both can be used. “ open open-> Reading and writing write/read-> close close” Mode to operate . namely socket It's a special document , some socket Function is the operation on it ( read / Write IO、 open 、 close ).

3.Socket Basic operation
since socket yes “open->write/read->close” A manifestation of the pattern , that socket The function interface corresponding to these operations is provided . Let's say TCP For example , Introduce socket The interface function of .

Int socket(int domain, int type, int protocol);.
Socket Function corresponds to the open operation of a normal file . The open operation of a normal file returns a file description word , and socket() Used to create a socket The descriptor (socket descriptor), It uniquely identifies a socket. This socket Descriptors are the same as document descriptors , It is used for subsequent operations , Take it as a parameter , Through it to do some reading and writing operations .
As to fopen Passed in different parameter values for , To open different files . establish socket When , You can also specify different parameters to create different socket The descriptor ,socket The three parameters of the function are :
Domain: Protocol domain , Also known as the protocol family . Common protocol families are :AF_INET、AF_INET6、AF_LOCAL( Or called AF_UNIX,Unix Domain socket)、AF_ROUTE wait . The protocol family decided socket Address type of , The corresponding address must be used in the communication , Such as AF_INET Decide to use Ipv4 Address (32 position ) And port (16 position ) The combination of 、AF_UNIX Decided to use an absolute pathname as the address .
Type: Appoint socket type . frequently-used socket Type a :SOCK_STREAM、SOCK_DGRAM、SOCK_RAW、SOCK_PACKET、SOCK_SEQPACKET wait .
Protocol: Designated agreement . Common protocols are :IPPROTO_TCP、IPPTOTO_UDP、IPPROTO_SCTP、IPPROTO_TIPC etc. , They correspond to each other TCP Transfer protocol 、UPD Transfer protocol 、SCTP Transfer protocol 、TIPC Transfer protocol .
It's not the one above type and protocol Can be combined at will , Such as SOCK_STREAM You can't talk to IPPROTO_UDP Combine . When protocol by 0 when , Will automatically select type Default protocol corresponding to type .
When we call socket Create a socket when , Back to socket The descriptor exists in the protocol family space , But there is no specific address . If you want to assign an address to it , You have to call bind() function , Otherwise, call connect()、listen() The system will automatically assign a port at random .

Int bind(int sockfd, const struct sockaddr addr, socklen_t addrlen);
As mentioned above bind() Function to assign a specific address in an address family to socket. For example, it corresponds to AF_INET、AF_INET6 Is to take a ipv4 or ipv6 The combination of address and port number is assigned to socket.
Sockfd: namely socket Description words , It's through socket() Function creation , A unique logo socket.Bind() Function is to bind the descriptor to a name .
Addr: One const struct sockaddr
The pointer , Point to bind to sockfd Agreement address for . This address structure is created according to the address socket When the address protocol family is different ,
Such as ipv4 The corresponding is :

Struct sockaddr_in
{
    
		Sa_family_t 	sin_family;
		In_port_t		sin_port;
		Struct in_addr sin_addr;
}
	
Struct in_addr
{
    
	Uint32_t 	s_addr;
}

Ipv6 The corresponding is :

Struct sockaddr_in6
{
    
	Sa_family_t	sin6_family;
	In_port_t 	sin6_port;
	Uint32_t		sin6_flowinfo;
	Struct in6_addr sin6_addr;
	Uint32_t		sin6_scope_id;
}
Struct in6_addr
{
    
	Unsigned char s6_addr[16]
}
Addrlen: It corresponds to the length of the address .
 Usually the server will bind a well-known address when it starts ( Such as ip Address + Port number ), Used to provide services , Customers can connect to the server through it ; And the client doesn't have to specify , The system automatically assigns a port number and its own ip Address combination . That's why the server is usually on listen We'll call bind(), And the client will not call , But in connect() The system randomly generates a .

Int listen(int sockfd, int backlog);
Int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);
Listen The first parameter of the function is the one to listen to socket Description words , The second parameter is the corresponding socket The maximum number of connections that can be queued .Socket() Function created socket The default is an active type ,listen Function will socket Become passive , Waiting for customer's connection request .
Connect The first parameter of the function is the client's socket Description words , The second parameter is the server socket Address , The third parameter is zero socket The length of the address . The client calls connect Function to establish and TCP Server connection .

Int accept(int sockfd, sturct sockaddr *addr, socklen_t *addrlen);
TCP One call from the server socket(),bind(),listen() after , Will monitor the designated socket Address .TCP The client calls... At one time socket()、connect() After that, I went to TCP The server sent a connection request .TCP After the server listens for the request , It will start accept() Function to accept the request , So the connection is established . Then we can start the Internet I/O Operation , That is, reading and writing similar to ordinary documents I/O operation .
Accept The first parameter of the function is... Of the server socket Description words , The second parameter is pointing to struct sockaddr* The pointer to , Used to return the protocol address of the client , The third parameter is the length of the protocol address . If accept success , So its return value is a new description word automatically generated by the kernel , Representing and returning customers TCP Connect .
 Be careful :accept The first parameter of is the... Of the server socket Description words , It's the server that starts calling socket() Function generated , It's called listening socket Description words ; and accept The function returns connected socket Description words . A server usually only creates one listener socket Description words , It exists throughout the lifetime of the server . The kernel creates a connection for each client connection accepted by the server process socket Description words , When the server completes the service to a certain customer , Corresponding connected socket The descriptors are closed .

 thus , The server has established a connection with the client . You can call the network I/O Read and write it , Realize the communication between different processes in the network .
Ssize_t sendmsg(int sockfd, const struct msghdr *msg, int flags);
Ssize_t recvmsg(int sockfd, struct msghdr *msg, int flags);
Sszie_t read(int fd, void *buf, size_t count);
Ssize_t write(int fd, const void *buf, size_t count);
Read The function is responsible for from fd Read content in , When the reading is successful ,read Returns the actual number of bytes read , If the value returned is 0 Indicates that the end of the file has been read , Less than 0 Indicates an error occurred . If the error is EINTR Explain that the read is caused by an interrupt , If it is ECONNREST Indicates that there is a problem with the network connection .
Write Function will buf Medium nbytes Bytes write to file descriptor fd, Returns the number of bytes written on success , Return... On failure -1, And set up errno Variable . In a web program , When we write to the socket file descriptor, there are two possibilities :write The return value of is greater than 0, Indicates that some or all of the data has been written ; The value returned is less than 0, There was a mistake , It needs to be handled according to the error type . If the error is EINTR Indicates an interrupt error occurred while writing . If EPIPE Indicates that there is a problem with the network connection ( The other party has closed the connection ).

Int close(int fd);	
Close One TCP socket The default behavior is to socket Mark as closed , Then immediately return to the calling process . This descriptor can no longer be used by the calling process , That is, they can no longer act as read or write The first parameter of .
 Be careful :close The operation just makes the corresponding socket Reference count of descriptive words -1, Only if the reference count is 0 When , Will trigger TCP The client sends a termination request to the server .

Socket in TCP Three handshakes are established :
TCP To establish a connection “ Three handshakes ”, That is, three packets are exchanged . The general flow is as follows :
: The client sends a... To the server SYN J
: The server responds to the client with a SYN K, Also on SYN J Confirm ACK J+1
: The client sends a confirmation to the server ACK K+1
 Insert picture description here
As you can see from the diagram , When the client calls connect when , Connection request triggered , Send to server SYN J package , This is a connect Go into blocking mode ; The server listens for connection requests , Be subjected to SYN J package , call accept Function to receive the request and send it to the client SYN K,ACK J+1, At this time accept Go into blocking mode . The client receives... From the server SYN K, ACK J+1 after , At this time connect return , Also on SYN K Confirm . Server received ACK K+1 when ,accept return , Now the three handshakes are over , Connection is established .
summary : Client's connect On the second return of the three handshakes , On the server side accept On the third return

Socket in TCP Four handshakes to release the connection
 Insert picture description here

The process is as follows :
: An application process first calls close Active close connection , At this time TCP Send a FIN M;
: The other end receives FIN M after , Perform passive shutdown , For this FIN Confirm . Its reception is also passed to the application process as a file Terminator , because FIN It is assumed that the application process will no longer receive additional data on the corresponding connection .
: After a while , Receive the application process call of the end of file close Turn it off socket. This leads to its TCP Also send a FIN N.
: Received this FIN Source sender of TCP Confirm it
So there's one in every direction FIN and ACK.

原网站

版权声明
本文为[Jacob_ Always]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202200540428637.html