针对协议命令字处理函数

来源:互联网 发布:java 节假日判断 编辑:程序博客网 时间:2024/05/17 15:39

我们在处理命令字协议的时候例如以下协议,aa tt  05 06 09 bb  其中aa tt是协议头,05是命令字 ,06是数据长度,09是数据内容,bb是协议尾。

针对这种协议。我们一般在处理命令字的时候大多数使用的都是switch case进行命令字的处理。但是如果再处理非常多的命令字的时候我们就不得不

建立更多的case语句进行处理。

下面的程序是使用的类似于注册命令字的形式,当一条协议发送过来后,通过查找相应的命令字来处理不同的任务。

下面的程序已经在linux上进行测试过

#include <stdio.h>#include <string.h>#define MAX_CMD_NUM     (50)#if 1//两种定义方式都可以enum{        FIRST    =0x01,        TWO      =0x02,};#else#define FIRST    (0x01)#define TWO      (0x02)#endiftypedef struct STUDENT{        int num;        char dat[20];}Student, *Studentinfo;//命令字处理函数typedef int (*fcmd_proc)(Studentinfo std); //自己定义多少个参数和参数类型eg(Studentinfo std,int i, int h);struct PROCESS_CMD{ //命令字处理结构体        unsigned short  cmd_num;        unsigned char   command[MAX_CMD_NUM];        fcmd_proc process_cmd[MAX_CMD_NUM];}proc_cmd;//注册命令字处理函数static void reg_cmd_proc(unsigned char command, fcmd_proc fproc){        proc_cmd.command[proc_cmd.cmd_num] = command;        proc_cmd.process_cmd[proc_cmd.cmd_num] = fproc;        proc_cmd.cmd_num += 1;}static int proc_first_cmd(Studentinfo std){        printf("1=  %d,%s\n",std->num,std->dat);}static int proc_two_cmd(Studentinfo std){        printf("2=  %d,%s\n",std->num,std->dat);}//所有的命令字在这里注册void register_all_command(void){        reg_cmd_proc(FIRST, proc_first_cmd);        reg_cmd_proc(TWO,   proc_two_cmd);}//查找并处理命令int process_command(Studentinfo std){        int i;        for(i = 0; i< proc_cmd.cmd_num ;++i)        {                if(proc_cmd.command[i] == std->num)                {                        printf("cmd : 0x%x\n",std->num);                        return proc_cmd.process_cmd[i](std);                }        }}int main(int argc,char *argv[]){        Student std;        int flags = 1;        register_all_command();//注册所有命令字        while(1)        {                printf("请输入num和名字eg:33,xiaobing  :");                scanf("%d,%s",&std.num,std.dat);                process_command(&std);        }        return 0;}




0 0
原创粉丝点击