PracticeDev/study_clang/zmq/zmq_experiment/server.c

105 lines
3.0 KiB
C
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*****************************************************************************
* Copyright: 2016-2026, Ieucd Tech. Co., Ltd.
* File name: server.c
* Description: 用于实现zmq多线程收发结构体消息的通信框架。
* Author: TLSong
* Version: V0.0.1
* Date: 2020/7/7
* History:
* 2020/7/7 创建文件。
* *****************************************************************************/
#include <zmq.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <assert.h>
#include <float.h>
#include <limits.h>
#include <pthread.h>
#include "data_mode.h"
void *value_server(void *args)
{
Msg max_msg = {INT_MAX, CHAR_MAX, SHRT_MAX, LONG_MAX, FLT_MAX, DBL_MAX, "Hello Max Value!"};
Msg min_msg = {INT_MIN, CHAR_MIN, SHRT_MIN, LONG_MIN, FLT_MIN, DBL_MIN, "Hello Min Value!"};
Msg random_msg = {233, 'h', 244, 255, 0.01, 0.0001, "Hello Random Value!"};
// Socket to talk to clients
void *context = zmq_ctx_new ();
void *responder = zmq_socket (context, ZMQ_REP);
int rc = zmq_bind (responder, "tcp://*:5555");
assert (rc == 0);
while (1) {
char buffer [10];
zmq_recv (responder, buffer, 10, 0);
printf ("Received: %s\n",buffer);
sleep (1); // Do some 'work'
Msg send_msg;
if(strcmp(buffer,"MAX")==0)
send_msg = max_msg;
else if(strcmp(buffer,"MIN")==0)
send_msg = min_msg;
else
send_msg = random_msg;
zmq_send (responder, &send_msg, sizeof(send_msg), 0);
printf ("Sned message: \n");
printf ("---------------start---------------\n");
printf ("int: %d\n",send_msg.Int);
printf ("char: %c\n",send_msg.Char);
printf ("short: %hd\n",send_msg.Short);
printf ("long: %ld\n",send_msg.Long);
printf ("float: %d\n",send_msg.Float);
printf ("double: %d\n",send_msg.Double);
printf ("String: %s\n",send_msg.String);
printf ("--------------- end ---------------\n");
}
}
void *sub_weather(void *args)
{
void* context = zmq_ctx_new();
assert(context != NULL);
void* subscriber = zmq_socket(context, ZMQ_SUB);
assert(subscriber != NULL);
int ret = zmq_connect(subscriber, "tcp://localhost:5556");
assert(ret == 0);
ret = zmq_setsockopt(subscriber, ZMQ_SUBSCRIBE, "", 0);
assert(ret == 0);
while(1)
{
printf("into while\n");
char szBuf[1024] = {0};
ret = zmq_recv(subscriber, szBuf, sizeof(szBuf) - 1, 0);
if (ret > 0)
{
printf("%s\n", szBuf);
}
}
zmq_close(subscriber);
zmq_ctx_destroy(context);
}
int main (void)
{
int value_ret, sub_weather_ret;
pthread_t value_pth, sub_weather_pth; //线程ID变量
// 参数创建的线程ID线程参数调用函数函数参数
value_ret = pthread_create(&value_pth,NULL,value_server,NULL);
sub_weather_ret = pthread_create(&sub_weather_pth,NULL,sub_weather,NULL);
pthread_join(value_pth,NULL); // 等待线程结束
//pthread_join(sub_weather_pth.NULL);
return 0;
}