Socket message flow introduction and C code implementation, socket message flow code

Source: Internet
Author: User

Socket message flow introduction and C code implementation, socket message flow code

In actual software development, socket programming is often involved, that is, using socket to complete message interaction and command execution. This article uses a C program to explain the entire message execution process of the socket in Linux.

C program example

/*************************************** * ******************************** All Rights Reserved (C) 2015, Zhou Zhaoxiong. ** File name: TestSocket. c * File ID: none * Content summary: test the entire process from socket creation to completion * Other Instructions: none * Current version: V1.0 * Author: Zhou Zhaoxiong * completion 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 1024 # define SERVERPORT 89 99 # define IPADDR "10.116.32.10" // redefine the Data Type typedef unsigned char UINT8; typedef signed int INT32; typedef unsigned int UINT32; typedef INT32 SOCKET; typedef struct sockaddr_in SOCKADDR_IN; typedef struct sockaddr * PSOCKADDR; // global variable UINT8 g_iStart = 0; UINT8 g_iFinish = 0; /*************************************** * ******************************** function description: main function * input parameter: none * output parameter: none * return value: none * Other Description: No * modify date version number modifier modify content *-- ----------------------------------------------------------------- * 20150608 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 c Lient_addrss = {0}; pthread_t tid = pthread_self (); while (1) {// create socket close (sockefd); sockefd = socket (AF_INET, SOCK_STREAM, 0 ); if (INVALID_SOCKET = sockefd) {continue;} // bind the specified IP address and port local_address.sin_family = AF_INET; region = htons (SERVERPORT); region = 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 the specified 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 ;}// enable listening iRet = listen (sockefd, 10); if (iRet <0) {printf ("FAILED to stratup the listener! \ N "); return-1 ;}// obtain the while (1) {iLenth = sizeof (client_addrss) from the listener queue cyclically; clientSocketfd = accept (sockefd, (struct sockaddr *) & 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 ("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; // print the message UINT8 szCmd [1024] = {0}; sprintf (szCmd, "This is a test for SOCKET! \ N "); printf (" The command is: % s \ n ", szCmd); g_iFinish = 1; // set The end ID 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 the message that ends this 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
Through the above code, we can see that the entire message flow of the socket is:
Step 1: Create a socket.
Step 2: bind the specified IP address and port. If binding fails, skip to the first step.
Step 3: Start the listener. If no message is monitored, the program remains in the listening State. If the message is listened to, execute the next step.
Step 4: cyclically retrieve messages from the listener queue and perform related operations based on the message content.
Step 5: after the operation is completed, the relevant message is returned to the message sending module.

Multiple socket functions are involved in the entire process, including close, socket, inet_addr, setsockopt, bind, listen, accept, recv, and send, for more information about these functions, visit the internet.

Makefile content
This program is compiled and run in Linux. The content of the makefile file is:

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

Program running result
A self-developed message sending Tool sends three messages to the program consecutively. The result is as follows:

zhou@Linux:~/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 is successfully bound to an IP address and port, it remains in the listening state. As long as a message is sent, it will perform subsequent message processing.

Summary
Socket has a long history and is also widely used in actual software development projects. As a qualified software development engineer, you must master the usage methods.

My public account: zhouzxi. Please scan the following QR code:

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.