当前位置: 首页 > 工具软件 > tcpdaemon > 使用案例 >

TCP 通讯服务端平台/库 tcpdaemon 更新至 v1.2.2

漆雕疏珂
2023-12-01

1.2.2 2017-06-06 calvin

  • 封装更多的IO多路复用代码进tcpdaemon,使用者用tcpmain返回值设置等待事件
  • IO多路复用模型新增超时机制

1.概述
tcpdaemon是一个TCP通讯服务端平台/库,它封装了众多常见服务端进程/线程管理和TCP连接管理模型(Forking、Leader-Follow、IO-Multiplex、WindowsThreads Leader-Follow),使用者只需加入TCP通讯数据收发和应用逻辑代码就能快速构建出完整的TCP应用服务器。

...

2.使用示例
2.1.服务模型Forking,链接模式1,接收HTTP请求报文然后发送HTTP响应报文

使用者只需编写一个函数tcpmain,实现同步的接收HTTP请求报文然后发送HTTP响应报文回去

$ vi test_callback_http_echo.c
#include "tcpdaemon.h"

_WINDLL_FUNC int tcpmain( struct TcpdaemonServerEnvirment *p_env , int sock , void *p_addr )
{
    char    http_buffer[ 4096 + 1 ] ;
    long    http_len ;
    long    len ;

    /* 接收HTTP请求 */
    memset( http_buffer , 0x00 , sizeof(http_buffer) );
    http_len = 0 ;
    while( sizeof(http_buffer)-1 - http_len > 0 )
    {
        len = RECV( sock , http_buffer + http_len , sizeof(http_buffer)-1 - http_len , 0 ) ;
        if( len == 0 )
            return TCPMAIN_RETURN_CLOSE;
        if( len == -1 )
            return TCPMAIN_RETURN_ERROR;
        if( strstr( http_buffer , "\r\n\r\n" ) )
            break;
        http_len += len ;
    }
    if( sizeof(http_buffer)-1 - http_len <= 0 )
    {
        return TCPMAIN_RETURN_ERROR;
    }

    /* 发送HTTP响应 */
    memset( http_buffer , 0x00 , sizeof(http_buffer) );
    http_len = 0 ;
    http_len = sprintf( http_buffer , "HTTP/1.0 200 OK\r\nContent-length: 17\r\n\r\nHello Tcpdaemon\r\n" ) ;
    SEND( sock , http_buffer , http_len , 0 );

    return TCPMAIN_RETURN_CLOSE;
}

编译链接成test_callback_http_echo.so

$ gcc -g -fPIC -O2 -Wall -Werror -fno-strict-aliasing -I. -I/home/calvin/include/tcpdaemon  -c test_callback_http_echo.c
$ gcc -g -fPIC -O2 -Wall -Werror -fno-strict-aliasing -shared -o test_callback_http_echo.so test_callback_http_echo.o -L. -L/home/calvin/lib -lpthread -ldl

用tcpdaemon直接挂接即可

$ tcpdaemon -m IF -l 0:9527 -s test_callback_http_echo.so -c 10 --tcp-nodelay --logfile $HOME/log/test_callback_http_echo.log --loglevel-debug
可```  
执行程序tcpdaemon所有命令行参数可以不带参数的执行而得到

$ tcpdaemon
USAGE : tcpdaemon -m IF -l ip:port -s so_pathfilename [ -c max_process_count ]

              -m LF -l ip:port -s so_pathfilename -c process_count [ -n max_requests_per_process ]
    other options :
              -v
              [ --daemon-level ]
              [ --work-path work_path ]
              [ --work-user work_user ]
执行后可在$HOME/log下可以看到tcpdaemon的日志。

通过curl发测试请求

$ curl "http://localhost:9527/"
Hello Tcpdaemon

测试成功!

所有代码在源码安装包的test目录里下可以找到

...

 类似资料: