Introduction to the socket message flow and its C code implementation

Source: Internet
Author: User

In the actual software development work, often involves the socket programming, namely uses the socket to complete the message interaction and the command execution. In this paper, a C program is presented to explain the entire message execution flow of the socket under Linux.

C Program Examples

/*********************************************************************** All rights reserved (C), Zhou Zhaoxiong. * * File name: testsocket.c* file ID: None * Content summary: Test the entire process of socket from creation to end * Other instructions: none * Current version: v1.0* Author: Zhou zhaoxiong* finish Date: 20150608********* **************************************************************/#include <stdio.h>#include <stdlib.h>#include <string.h>#include <errno.h>#include <netinet/in.h>#include <sys/socket.h>//Macro definition#define INVALID_SOCKET-1#define SOCKET_ERROR-1#define Buffer_len 1024x768#define ServerPort 8999#define IPADDR "10.116.32.10"//Redefine data typetypedef unsigned CharUINT8;typedef signed   intINT32;typedef unsigned intUINT32;typedefINT32 SOCKET;typedef structSockaddr_in sockaddr_in;typedef structSOCKADDR *psockaddr;//global variableUINT8 G_istart =0; UINT8 G_ifinish =0;/*********************************************************************** Function Description: main function * input parameter: none * output parameter: no * return value: None * Other instructions: no * Modified date version number modified content *-------------------------------------------------------------------* 2 0150608 V1.0 Zhou Zhaoxiong Create ***********************************************************************/
     INT32 Main () {INT32 IRet =-1; INT32 status =0; INT32 Itempvar =0; UINT32 Ilenth =0; UINT8 Szbuffer[buffer_len] = {0};    SOCKET sockefd = Invalid_socket; SOCKET CLIENTSOCKETFD = {0}; Sockaddr_in local_address = {0}; Sockaddr_in Client_addrss = {0}; pthread_t tid = pthread_self (); while(1)    {//Create socketClose (SOCKEFD); SOCKEFD = socket (af_inet, Sock_stream,0);if(Invalid_socket = = SOCKEFD) {Continue; }//Bind specify IP address and portlocal_address.sin_family = af_inet;        Local_address.sin_port = htons (ServerPort);        Local_address.sin_addr.s_addr= inet_addr (IPADDR);        status = Socket_error; Itempvar =1;if(SetSockOpt (SOCKEFD, Sol_socket, SO_REUSEADDR, (int*) &itempvar,sizeof(Itempvar)) == -1)        {printf("SetSockOpt so_reuseaddr failed! ERROR[%D] errorinfo[%s]\n ", errno, Strerror (errno)); Close (sockefd);;Continue; } status = Bind (SOCKEFD, (psockaddr) &local_address,sizeof(sockaddr_in));//Bind specify IP address and port        if(Status = = Socket_error) {Close (SOCKEFD);;printf("FAILED to bind ipaddr:%s!\n", ipaddr);Continue; }Else{printf("succeeded to bind ipaddr:%s, port:%d!\n", ipaddr, ServerPort); Break; }    }//Start monitoringIRet = Listen (SOCKEFD,Ten);if(IRet <0)    {printf("FAILED to Stratup the listener!\n");return-1; }//loop gets from the listening queue     while(1) {Ilenth =sizeof(CLIENT_ADDRSS); CLIENTSOCKETFD = Accept (SOCKEFD, (structSOCKADDR *) &client_addrss, &ilenth);if(clientsocketfd = = Invalid_socket) {printf("The client socket is invalid!\n");Continue; }printf("------------------------------------------\ n");printf("Accept msg from Sendmsgtool successfully!\n");memset(Szbuffer,0x00,sizeof(Szbuffer)); Ilenth = recv (Clientsocketfd, Szbuffer, buffer_len-1,0);if(Ilenth <=0)        {printf(the Server receive data failed! strerror=%s.\n ", Strerror (errno));Continue; }printf("Receive data:%s\n", szbuffer);if(0==strncmp(Szbuffer,"Start test.\r\n",strlen("Start test.\r\n")) {G_istart =1;//Perform related actions, print messagesUINT8 szcmd[1024x768] = {0};sprintf(Szcmd,"This was a test for socket!\n");printf("The command is:%s\n", Szcmd); G_ifinish =1;//Set the end tag to 1} while(1)        {if(1= = G_ifinish) {memset(Szbuffer,0x00,sizeof(Szbuffer));sprintf(Szbuffer,"Task completed\r\n");if(Send (CLIENTSOCKETFD, Szbuffer,strlen(Szbuffer),0) <0)//Send a message to end this round session{printf("Send close msg failed!\n"); }Else{printf("Send close msg ok!\n"); }printf("------------------------------------------\ n"); G_ifinish =0; G_istart =0; Break; }        }    }return 0;}

Detailed Procedures
With the above code, we can see that the entire message flow of the socket is:
The first step is to create the socket.
The second step is to bind the specified IP address and port. If the binding fails, skip to the first step.
Step three, start monitoring. If the message is not heard, the program is in a listening state, and if the message is heard, the next step is performed.
In the fourth step, the loop gets the message from the listening queue and performs the related actions based on the message content.
In the fifth step, the operation is completed and the relevant message is returned to the module that sent the message.

In the whole process, it involves a number of socket functions, including: Close, Socket, inet_addr, setsockopt, bind, listen, accept, recv, send, etc., the detailed introduction of these functions, please check the Internet.

Makefile File Contents
This program is compiled and run under Linux, the contents of the makefile file are:

TestSocket : TestSocket.c    gcc -c -g TestSocket.c    gcc -g -o release/TestSocket TestSocket.o    rm *.o

Program Run Results
A self-developed message sending tool continuously sends three messages to the program, with the following results:

[email protected]:~/zhouzhaoxiong/testsocket/ release> testsocketsucceeded to bind ipaddr:10.116.32.139, port:8999!----------------- ------------------------- Accept msg from Sendmsgtool successfully! Receive Data:start test. The command is:this is a test for socket! send close msg OK!------------------------------------------ ------------------------------------------Accept msg from Sendmsgtool successfully! Receive Data:start test. The command is:this is a test for socket! Send close msg OK!------------------------------------------ ---------------------- --------------------Accept msg from Sendmsgtool successfully! Receive Data:start test. The command is:this is a test for socket! Send Close msg OK!------------------------------------------  

As you can see, after the program successfully binds the IP address and port, it is in a listening state. Whenever a message is sent, it executes the subsequent message processing.

Summary
Socket has a very long history, but also in the actual software development projects have a wide range of applications. As a qualified software Development engineer, we must master its use method.

My public number: ZHOUZXI, please scan the following two-dimensional code:

Introduction to the socket message flow and its C code implementation

Related Article

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.