#endif
/*
*handle.c
*
*/
#include "handle.h"
#include "network.h"
HANDLER* init_handle()
{
int len = sizeof(HANDLER);
HANDLER* handler= (HANDLER*) malloc(len);
if (handler == NULL) {
fprintf(stderr, "init_handlers malloc error, errno: %d %m\n", errno);
return NULL;
}
memset(handler, 0, len);
//为线程创建对应的消息队列
MSG_QUEUE* msg_queue =create_msg_queue();
if(msg_queue==NULL){
free(handler);
fprintf(stderr, "create msg queue error, errno: %d %m\n", errno);
return NULL;
}
handler->qmsg=msg_queue;
//worker->qmsg=msg_queue;
handler->send_port=conf->center_port;
strcpy(handler->send_ip,conf->center_ip);
return handler;
}
static int create_sock(const char *ip, short port){
int sockfd=0;
if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0){
herror("Init socket error!");
return -1;
}
struct sockaddr_in addr;
socklen_t addrlen = sizeof(addr);
memset(&addr, 0, addrlen);
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = ip == NULL ? INADDR_ANY : inet_addr(ip);
addr.sin_port = htons(port);
if(connect(sockfd,(struct sockaddr*)&addr,sizeof(addr))<0){
//fprintf(stderr, "connect the center server error, errno: %d %m\n", errno);
return -1;//0表示成功,-1表示失败
}else{
printf("handler socket create success!\n");
return sockfd;
}
}
static void *handle_thread_run(void *arg)
{
HANDLER *handler= (HANDLER*) arg;
int sock_fd=create_sock(NULL,handler->send_port);//ip 暂时设为本地
if(sock_fd<0){
fprintf(stderr, "connect the center server error, errno: %d %m\n", errno);
}else{
handler->send_sock=sock_fd;
printf("connect the center server success!handler _id:%d\n",sock_fd);
}
//char msg_buf[2048];
while(1){
//send(sock_fd,"test",5,0);
//bzero(msg_buf,2048);
if(handler->qmsg->size>0){
MSG *tmp_msg;
tmp_msg=malloc(sizeof(MSG)); /*申请新结点*/
//得到消息数组指针
if(get_msg(handler->qmsg,tmp_msg)<0){
fprintf(stderr, "get msg from msg_queue error, errno: %d %m\n", errno);
free(tmp_msg);
continue;
}else{
printf("get a msg success!\n");
//handle the protocol CMD
uint16 msg_id=0;
memcpy(&msg_id,tmp_msg->buf,2);
msg_id=ntohs(msg_id);
printf("recv id %d.\n",msg_id);
//处理指令应答
if(tmp_msg->c->rsp_status==1){
//判断消息是否是平台等待终端应答的消息
if(msg_id==tmp_msg->c->waiting_cmd_rsp){
tmp_msg->c->rsp_status=2;
printf("command zd response success.rsp_id:%x\n",msg_id);
}
}
//执行协议指令
if (msg_id < g_akg_connected_id &&AKG_FUNC[msg_id]) {
if (AKG_FUNC[msg_id](tmp_msg)==0) {
//执行处理函数成功,释放tmp_msg
free(tmp_msg);
}
} else {
fprintf(stderr, "invalid msg_id:%x.\n", msg_id);
continue;
}
}
}
}
return NULL;
}
int start_handle(HANDLER* handler){
pthread_t thread_id;
if(pthread_create(&thread_id, NULL, handle_thread_run,handler) != 0) {
fprintf(stderr, "start_handle create thread error, errno: %d %m\n", errno);
return -1;
}
handler->thread_id=thread_id;
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文:http://blog.csdn.net/ozuoqi/article/details/47426521