TCP/IP network Programming Learning note _6--defining application layer protocols

Source: Internet
Author: User
Tags htons

Preface: The previous chapter wrote an echo customer service side, review, customer service is the loop read the known length of the data, but more often we can not know the length of the data in advance, then how to send and receive data at this time? What is needed is the definition of the application layer protocol. such as: In the previous section of the ECHO program defined "Receive Q immediately terminate the connection" such a protocol (rule), is the application layer protocol. Similarly, the process of sending and receiving data requires that rules be set to represent the boundaries of the data, or to inform the size of the sending and receiving data in advance. The so-called Application layer protocol is the set of rules that are defined incrementally during the service-side/client-side implementation. It can be seen that the application layer protocol is not an enigmatic existence, but a rule for the implementation of a particular program.

Application layer protocol design of Calculator program

Let's try to design an application-level protocol that implements the Calculator program (customer service sends the number of operations, operands, operators, and the server receives the data to end to the client):

    • The customer service side is connected to the server side and passes the operands in 1-byte integers as a number.
    • Each operand that the customer service side passes to the server is a 4-byte integer data.
    • After each operand is passed, the operator is then passed, and the operator occupies 1 bytes.
    • The server returns the result of the operation as a 4-byte integer to the customer service.
    • The client terminal terminates the connection to the server after obtaining the result of the operation.

      These are the application layer protocols that are designed to implement specific programs, and see the specific code implemented under these protocol rules.

Calculator program source code
    • Customer Service side
////Main.cpp//Hello_client////Created by app05 on 15-7-6.//Copyright (c) 2015 APP05. All rights reserved.//#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include <arpa/inet.h>#include <sys/socket.h>#define BUF_SIZE 1024x768#define RLT_SIZE 4#define OPSZ 4voidError_handling (Char*message) {fputs(message, stderr); FPUTC (' \ n ', stderr);Exit(1);}intMainintargcConst Char* argv[]) {intSockCharOpmsg[buf_size];intresult, opnd_cnt, I;structSockaddr_in Serv_adr;if(ARGC! =3) {printf("Usage:%s <IP> <port> \ n", argv[0]);Exit(1); } sock = socket (pf_inet, Sock_stream,0);if(Sock = =-1) {error_handling ("socket () error"); }memset(&serv_adr,0,sizeof(SERV_ADR));    serv_adr.sin_family = af_inet; SERV_ADR.SIN_ADDR.S_ADDR = inet_addr (argv[1]); Serv_adr.sin_port = htons (Atoi (argv[2]));if(Connect (sock,structSOCKADDR *) &serv_adr,sizeof(SERV_ADR)) == -1) Error_handling ("Connect () Error");Else        puts("The Connected of the ...");//Number of Operations (1 bytes)    fputs("Operand count:", stdout);scanf("%d", &opnd_cnt); opmsg[0] = (Char) opnd_cnt;//operand (4 bytes per account)     for(i =0; i < opnd_cnt; i++) {printf("Operand%d:", i +1);scanf("%d", (int*) &opmsg[i * opsz +1]); } fgetc (stdin);//read out the characters in the buffer \ n    //Operator (1 bytes)    fputs("Operator:", stdout);scanf("%c", &opmsg[opnd_cnt * opsz +1]); Write (sock, opmsg, opnd_cnt * opsz +2); Read (sock, &result, rlt_size);//Because the server returns only 4 bytes of results, it can be read one time, so there is no need to loop read    printf("Operation result:%d \ n", result); Close (sock);return 0;}
    • Service side
////Main.cpp//Hello_server////Created by app05 on 15-7-6.//Copyright (c) 2015 APP05. All rights reserved.///* Description: Whether the data transfer needs to be recycled, mainly look at the size of the transmitted data, if it is longer, it may be transmitted several times, and TCP receive and transmit is not necessarily equal, at this time, in order to read the data correctly needs to be read according to the size of the transmitted data. This is a common mistake that many novices make, be sure to note that TCP has no data boundaries. */#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include <arpa/inet.h>#include <sys/socket.h>#define BUF_SIZE 1024x768#define OPSZ 4voidError_handling (Char*message);intCalculateintOpnum,intOpnds[],CharOprator);intMainintargcConst Char* argv[]) {intServ_sock, Clnt_sock;CharOpinfo[buf_size];intresult, opnd_cnt, I;intRecv_cnt, Recv_len;structSockaddr_in Serv_adr, Clnt_adr; Socklen_t CLNT_ADR_SZ;if(ARGC! =2) {printf("Usage:%s <port> \ n", argv[0]);Exit(1); } Serv_sock = socket (pf_inet, Sock_stream,0);if(Serv_sock = =-1) Error_handling ("socket () error");memset(&serv_adr,0,sizeof(SERV_ADR));    serv_adr.sin_family = af_inet;    SERV_ADR.SIN_ADDR.S_ADDR = htonl (Inaddr_any); Serv_adr.sin_port = htons (Atoi (argv[1]));if(Bind (Serv_sock, (structSOCKADDR *) &serv_adr,sizeof(SERV_ADR)) == -1) Error_handling ("bind () Error");if(Listen (Serv_sock,5) == -1) Error_handling ("Listen () Error"); CLNT_ADR_SZ =sizeof(CLNT_ADR); for(i =0; I <5; i++) {opnd_cnt =0; Clnt_sock = Accept (Serv_sock, (structSOCKADDR *) &clnt_adr, &AMP;CLNT_ADR_SZ);//Number of operationsRead (Clnt_sock, &opnd_cnt,1);//operands and transport charactersRecv_len =0; while((OPND_CNT * opsz +1) (> Recv_len) {recv_cnt = Read (Clnt_sock, &opinfo[recv_len], buf_size-1);        Recv_len + = recv_cnt; }//Resultsresult = Calculate (opnd_cnt, (int*) Opinfo, Opinfo[recv_len-1]); Write (Clnt_sock, (Char*) &result,sizeof(result));    Close (Clnt_sock); } close (Serv_sock);return 0;}voidError_handling (Char*message) {fputs(message, stderr); FPUTC (' \ n ', stderr);Exit(1);}intCalculateintOpnum,intOpnds[],CharOP) {intresult = opnds[0], I;Switch(OP) { Case ' + ': for(i =1; i < opnum; i++) Result + = Opnds[i]; Break; Case '-': for(i =1; i < opnum; i++) Result-= Opnds[i]; Break; Case ' * ': for(i =1; i < opnum; i++) result *= opnds[i]; Break; }returnResult;}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

TCP/IP network Programming Learning note _6--defining application layer protocols

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.