Android--推送机制实现原理(四)-自己实现推送功能--心跳包

客户端、长连接和心跳包参考博客:http://blog.csdn.net/zh724738989/article/details/42007099


客户端


服务器端C代码(0.01版):

/**************服务器端程序***************/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <time.h>

int sockfd;
char *hbResponse = "ok";

void do_service(fd)
{
    char buf[100];
    char hb[] = "hb";
    int i;
    int len = recv(fd,buf,100,0);/*读取信息*/

    if(len < 0){
        printf("recv error!\n");
        exit(1);
    }else if (len == 0){
        printf("the client quit!\n");
    }else {
        buf[len] = '\0';
        printf("receive message: %s\n",buf);
    }


    if(i = strncmp(buf,hb,2) == 0){/*确认是心跳包*/   
        write(fd,hbResponse,strlen(hbResponse));
    }else {/*不是心跳包处理逻辑*/
        long t = time(0);
        char *s = ctime(&t);
        write(fd,s,strlen(s));
    }
}
void out_client(struct sockaddr_in clientaddr)
{
    char buffer[16];
    inet_ntop(AF_INET,&clientaddr.sin_addr.s_addr,buffer,sizeof(clientaddr));
    unsigned short port = ntohs(clientaddr.sin_port);
    printf("client ip:%s (%d)\n",buffer,port);
}


int main(int argc,char *argv[])
{
    if(argc < 2)
    {
        fprintf(stderr,"usage: %s port\n",argv[0]);
        exit(1);
    }

    /*create socket*/
    sockfd = socket(AF_INET,SOCK_STREAM,0);
    if(sockfd < 0)
    {
        fprintf(stderr,"socket: %s\n",strerror(errno));
        exit(1);
    }

    /*set ip and port*/
    struct sockaddr_in addr;
    memset(&addr,0,sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(atoi(argv[1]));
    addr.sin_addr.s_addr = INADDR_ANY; 

    /*bind ip and port*/
    int len = sizeof(addr);
    if(bind(sockfd,(struct sockaddr*)&addr,len) < 0)
    {
        fprintf(stderr,"bind: %s\n",strerror(errno));
        exit(1);
    }

    /*begin to listen*/
    if(listen(sockfd,10) < 0)
    {
        fprintf(stderr,"listen: %s\n",strerror(errno));
        exit(1);
    }

    while(1)
    {
        struct sockaddr_in clientaddr;
        int c_len = sizeof(clientaddr);
        int fd = accept(sockfd,(struct sockaddr*)&clientaddr,&c_len);
        if(fd < 0)
        {
            fprintf(stderr,"accept: %s\n",strerror(errno));
            continue;
        }
        while(1){

            out_client(clientaddr);
            do_service(fd);
            //close(fd);
        }
    }
    return 0;
}
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页