ipc--Flow Socket Communication

Source: Internet
Author: User

Linux interprocess communication-using streaming socketsAs mentioned earlier, the process of communicating between processes is on the same computer, while the process of communicating using the socket can be a process on the same computer and a process on a different computer that can be connected over a network. Usually we use sockets for network programming, which will simply tell you how to use a socket for simple network programming.  first, what is the socketA socket, or socket, is a communication mechanism whereby the development of a client/server (that is, the process of communicating) can be done on a local machine or across a network. This means that it can communicate with processes that are not on the same computer but are connected over the network to the computer. Because of this, the socket explicitly distinguishes the client from the server.  second, the properties of the socket the properties of a socket are determined by 3 properties, namely: domain, type, and protocol.  1. Socket domain It specifies the network media used in socket communication, the most common socket domain being af_inet, which refers to an Internet network. When a customer uses sockets to connect across a network, it needs to use the IP address and port of the server computer to designate a particular service on a networked machine, so when using the socket as the endpoint for communication, the server application must bind a port before starting the communication. The server waits for a client's connection on the specified port. The other domain Af_unix represents the Unix file system, which is the file input/output, and its address is the filename.  2. Socket type The Internet provides two communication mechanisms: stream and datagram (datagram), so that the type of socket is also divided into stream sockets and datagram sockets. This is where the flow sockets are mainly spoken.  flow sockets are specified by Type Sock_stream, which are implemented through TCP/IP connections in the Af_inet domain and are also common socket types in Af_unix. A stream socket provides an ordered, reliable, bidirectional byte-stream connection, so the data sent can be guaranteed not to be lost, duplicated, or ordered to arrive, and it has a mechanism to resend after a certain error.  relative to a stream socket is the datagram socket specified by type SOCK_DGRAM, which does not need to establish a connection and maintain a connection, which is usually implemented through the UDP/IP protocol in Af_inet. It has a limit on the length of data that can be sent, the datagram is transmitted as a separate network message, it may be lost, copied, or garbled, and UDP is not a reliable protocol, but it is relatively fast because it needs to always establish and maintain a connection.  3. Socket Protocolas long as the underlying transport mechanism allows more than one protocol to provide the required socket type, we can select a specific protocol for the socket. You typically only need to use the default values.  third, socket address each socket has its own address format, and for Af_unix domain sockets, its address is described by the struct sockaddr_un, which is defined in the header file Sys/un.h, which is defined as follows:
struct sockaddr_un{    sa_family_t sun_family; // Af_unix, it is a short integer type    Char        Sum_path[]; // path name };

For a af_inet domain socket, its address structure is described by sockaddr_in, which includes at least the following members:

struct sockaddr_in{    shortint            sin_family;   af_inetshort    int    sin_port;   Port number    struct in_addr        sin_addr;   IP Address };

and in_addr is defined as:

struct in_addr{    longint  s_addr;};
Iv. Workflow of client/server based on streaming socketsHow does the client/server system that uses the socket for process communication work?  1. Server-side first, the server application uses the system to invoke the socket to create a socket, which is a resource that the system allocates to a similar file descriptor for the server process, and it cannot be shared with other processes.  Next, the server process gives the socket a name, and we use the system to call bind to name the socket. The server process then begins to wait for the client to connect to the socket.  the system then calls listen to create a queue and use it to hold incoming connections from the customer.  Finally, the server accepts the client's connection through the system call accept. It creates a new socket that differs from the original named socket, which is used only to communicate with this particular client, whereas a named socket (that is, the original socket) is retained to continue processing connections from other customers.  2, the client the socket-based client is simpler than the server-side, and the client application first calls the socket to create an unnamed socket, and then calls connect with the server to establish a connection to the server, using its named socket as an address.  Once the connection is established, we can use the socket as the underlying file descriptor for bidirectional data communication.    Five, the interface and function of the flow socket the socket's interface functions are declared in the header files Sys/types.h and sys/socket.h.  1. Create socket--socket system call The function is used to create a socket and return a descriptor that can be used to access the socket, which is prototyped as follows:
int socket (intint int protocol);
The three parameters in the function correspond to the three socket properties mentioned earlier. The protocol parameter is set to 0 to indicate that the default protocol is used.  2. Naming (binding) Sockets--bind system calls This function names the socket created through the socket call, allowing it to be used by other processes. For Af_unix, when the function is called, the socket is associated to a file system pathname, and for af_inet, it is associated to an IP port number. The function prototypes are as follows:
int int Const struct sockaddr *address, size_t Address_len);
returns 0 on success, 1 when failed; 3. Create socket Queue (listen)--listen system call This function is used to create a queue to hold unhandled requests. Returns 0 on success, 1 on failure, and its prototype is as follows:
int Listen (intint. backlog);
backlog is used to specify the length of the queue, the number of incoming connections waiting to be processed cannot exceed this number, or the subsequent connection will be rejected, causing the client's connection request to fail. After the call, the program will always listen to the IP port, if there is a connection request, it is added to this queue.  4, accept the connection--accept system call The system call is used to wait for the client to establish a connection to the socket. The Accept system call is returned only if the client tries to connect to the socket specified by the socket parameter, that is, if there are no unhandled connections in the socket queue, the accept will block until a client establishes a connection. The Accept function creates a new socket to communicate with the customer and returns the descriptor for the new socket, which is the same type as the server listener socket type. Its prototype is as follows:
int Accept (intstruct sockaddr *address, size_t *address_len);
address is the location of the connection client, parameter Address_len specifies the length of the client structure, and if the customer address is longer than this value, it will be truncated.  5. Request Connection--connect system call This system call is used to allow the client program to connect to the server by establishing a connection between an unnamed socket and a server listener socket. Its prototype is as follows:
int Connect (intconststruct sockaddr *address, size_t Address_len);
the socket specified by the parameter socket is connected to the server socket specified by the parameter addres. Returns 0 on success and -1 on failure. 6. Close Socket--close system call This system call is used to terminate the socket connection on the server and the client, and we should always close the socket at both ends of the connection (server and client).  Vi. process using a streaming socket for communicationThe following uses multiple client programs and a server program to demonstrate how a socket is used for communication between processes.  SOCKSERVER.C is a server program that first creates a socket, then binds a port to listen to the socket, ignores the child process's stop message, and so on, then enters the loop, loops through the client to see if there are any clients connected to the server, and, if there is one, calls fork to create a child process to process the request. Use the Read system call to read the information sent by the client and use the write system calls to send information to the client. The work of this server is very simple, that is, the characters sent by the customer +1, and then sent back to the customer.  SOCKCLIENT.C is a client program, it is also to create a socket, and then connect to the designated IP Port server, if the connection is successful, use write to send information to the server, and then use read to obtain the server processing information, and then output.  the source code for server SOCKSERVER.C is as follows:
#include <unistd.h>#include<sys/types.h>#include<sys/socket.h>#include<netinet/inch.h>#include<signal.h>#include<stdio.h>#include<stdlib.h>intMain () {intSERVER_SOCKFD =-1; intCLIENT_SOCKFD =-1; intClient_len =0; structsockaddr_in server_addr; structsockaddr_in client_addr; //Create a flow socketSERVER_SOCKFD = socket (af_inet, Sock_stream,0);   //set the connection address and listening port that the server receivesserver_addr.sin_family = af_inet;//Specify network socketsSERVER_ADDR.SIN_ADDR.S_ADDR = htonl (Inaddr_any);//Accept connections for all IP addressesServer_addr.sin_port = htons (9736);//bind to Port 9736//binding (naming) SocketsBind (SERVER_SOCKFD, (structsockaddr*) &server_addr,sizeof(SERVER_ADDR)); //Create a socket queue, listen for socketsListen (SERVER_SOCKFD,5); //Ignore child process stop or exit signalsignal (SIGCHLD, sig_ign);  while(1)    {        CharCH =' /'; Client_len=sizeof(CLIENT_ADDR); printf ("Server waiting\n"); //Accept the connection, create a new socketCLIENT_SOCKFD = Accept (SERVER_SOCKFD, (structsockaddr*) &client_addr, &Client_len); if(fork () = =0)        {            //child process, read the information sent by the client, process the information, and then send it to the client .Read (CLIENT_SOCKFD, &ch,1); Sleep (5); CH++; Write (CLIENT_SOCKFD,&ch,1);            Close (CLIENT_SOCKFD); Exit (0); }        Else        {            //parent process, closing the socketClose (CLIENT_SOCKFD); }    }}

The source code for customer sockclient.c is as follows:

#include <unistd.h>#include<sys/types.h>#include<sys/socket.h>#include<netinet/inch.h>#include<arpa/inet.h>#include<stdio.h>#include<stdlib.h>intMain () {intSOCKFD =-1; intLen =0; structsockaddr_in address; intresult; CharCH ='A'; //Create a flow socketSOCKFD = socket (af_inet, Sock_stream,0); //set up information for the server to connect toaddress.sin_family = af_inet;//using network socketsADDRESS.SIN_ADDR.S_ADDR = inet_addr ("127.0.0.1");//Server AddressAddress.sin_port = htons (9736);//ports that the server listens onLen =sizeof(address); //Connect to Serverresult = Connect (SOCKFD, (structsockaddr*) &address, Len); if(Result = =-1) {perror ("ops:client\n"); Exit (1); }    //send a request to the serverWrite (SOCKFD, &ch,1); //getting data from the serverRead (SOCKFD, &ch,1); printf ("char Form server =%c\n", CH);    Close (SOCKFD); Exit (0);}
The results of the operation are as follows:  In this example, we started a server program and three client programs, and from the results of the operation, all the requests that the client sent to the server program were processed, that is, a becomes B. The read and write system calls that are used between the server and the client are the same as the read, write system calls that are blocked when using named pipes. For example, if the client program calls read, the read call is blocked if the server program does not write information to the socket of the specified client program.  Seven, the flow of sockets to impress megive me the feeling that a streaming socket is much like a named pipe, but it can make it very powerful to communicate with processes on different computers that are not on the same computer and are connected over a network.

ipc--Flow Socket communication

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.