python 发布
import zmq
from random import randrange
context = zmq.Context()
socket = context.socket(zmq.PUB)
socket.bind("tcp://*:5556")#这里一般不改
while True:
zipcode =1
temperature = 2
relhumidity =2
socket.send_string(f"{zipcode} {temperature} {relhumidity}")#传输三个信息
c++接收
#include <zmq.hpp>
#include <iostream>
#include <sstream>
int main (int argc, char *argv[])
{
zmq::context_t context ;
std::cout << "Collecting updates from weather server...\n" << std::endl;
zmq::socket_t subscriber (context, zmq::socket_type::sub);
subscriber.connect("tcp://localhost:5556");
const char *filter = (argc > 1)? argv [1]: "10001 ";
subscriber.setsockopt(ZMQ_SUBSCRIBE, "", 0);
for(int i =0;i<2;i++) {
zmq::message_t update;
int one_x, one_y, two_x,two_y,three_x,three_y,four_x,four_y;
subscriber.recv(&update);
std::istringstream iss(static_cast<char*>(update.data()));
iss >> one_x >> one_y >> two_x>>two_y >>three_x>>three_y >>four_x >>four_y ;
printf("%d 和%d 和 %d和 %d 和%d 和%d和 %d 和%d",one_x,one_y,two_x,two_y,three_x,three_y,four_x,four_y);
}
return 0;
}
效果如图: 循环两次打印的哈哈.
下面是自己的笔记,读者可以忽略不看
#include <zmq.hpp>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct ConmInfo
{
int car_one_x;
int car_one_y;
int car_two_x;
int car_two_y;
int car_three_x;
int car_three_y;
int car_four_x;
int car_four_y;
};
#define within(num) (int) ((float) num * random () / (RAND_MAX + 1.0))
int main () {
zmq::context_t context ;
zmq::socket_t publisher (context, ZMQ_PUB);
ConmInfo chong ;
publisher.bind("tcp://*:5556");
while (1) {
chong=ConmInfo{1,2,3,4,5,6,7,8};
zmq::message_t send_message(sizeof(ConmInfo));
memcpy(send_message.data(),&chong,sizeof(chong));
publisher.send(send_message);
}
return 0;
}
#include <zmq.hpp>
#include <iostream>
#include <sstream>
struct ConmInfo
{
int car_one_x;
int car_one_y;
int car_two_x;
int car_two_y;
int car_three_x;
int car_three_y;
int car_four_x;
int car_four_y;
};
int main (int argc, char *argv[])
{
zmq::context_t context ;
ConmInfo chong=ConmInfo{};
std::cout << "Collecting updates from weather server...\n" << std::endl;
zmq::socket_t subscriber (context, zmq::socket_type::sub);
subscriber.connect("tcp://10.11.31.56:5556");
const char *filter = (argc > 1)? argv [1]: "10001 ";
subscriber.setsockopt(ZMQ_SUBSCRIBE, "", 0);
int update_nbr;
long total_temp = 0;
while(true) {
zmq::message_t recv_message(sizeof(ConmInfo));
subscriber.recv(&recv_message);
memcpy(&chong,recv_message.data(),sizeof(chong));
printf("%d 和 %d 和%d ",chong.car_two_x,chong.car_one_y,chong.car_one_x);
}
return 0;
}
|