2020/2/17 custom protocol learning

1. Write a custom protocol, encapsulates the message sending and receiving module, src / msg.c follows:

#include "msg.h"
#include <unistd.h>
#include <string.h>
#include <memory.h>
#include <sys/types.h>

// calculate check code 计算校验码函数
static unsigned char msg_check(Msg *message)
{
    unsigned char s = 0;
    int i;
    for(i = 0; i < sizeof(message->head); i++)
    {
        s += message->head[i];
    }
    for(i = 0; i < sizeof(message->buff); i++)
    {
        s += message->buff[i];
    }
    return s;
}


// send a message: data in buff the data parameter buff is sent
int write_msg (int sockfd, char * buff, size_t len)
{
    Msg Message;
    Memset (& Message, 0, the sizeof (Message));
    strcpy (Message. head, "iotek2012");
    the memcpy (message.buff, BUFF, len);
    message.checknum msg_check = (& Message);
    IF (Write (sockfd, & Message, the sizeof (Message))! = the sizeof (Message)) {
        return - . 1;
    }
    
}
// the receive message: data in the data buff buff received message parameter in a sockfd is read out
int read_msg (int sockfd, char * buff, size_t len)
{
    Msg message;
    Memset (& message, 0 , the sizeof (Message));
    size_t size;
    if((size = read(sockfd, &message, sizeof(message))) < 0){
        return -1;
    }
    else if(size == 0){
        return 0;
    }

    //check the code 检查校验码是否正确
    unsigned char s = msg_check(&message);
    if((s == (unsigned char)message.checknum) && (!strcmp("iotek2012",message.head))){//strcmp is a compare function for string
        memcpy(buff, message.buff, len);
        return sizeof(message);
    }
    return -1;
}

Wherein, size_t understood as the type unsigned integer unsigned int, which is defined in <stddef.h>, <stdio.h>, <stdlib.h>, <string.h>, <time.h>和<wchar.h>the standard C header files, increasing the portability of the code.

2. Compile test

 At the command line used when compiling, -Iinclude represent the current directory in the directory include as one of the search directory of header files
 

发布了5 篇原创文章 · 获赞 3 · 访问量 372

Guess you like

Origin blog.csdn.net/Xinyue_Lu/article/details/104347825