当前位置:   article > 正文

linux下如何通过rabbitmq进行简单的电脑间通信_rabbitmq本地进程间通信

rabbitmq本地进程间通信

SimpleAmqpClient中channel的构造函数是这样的:

static ptr_t AmqpClient::Channel::Create(const std::string & host = "127.0.0.1",
                                         int port = 5672,
                                         const std::string & username = "guest",
                                         const std::string & password = "guest",
                                         const std::string & vhost = "/",
                                         int frame_max = 131072 
                                         )  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

当我们成功地在一台电脑上实现了两个终端之间的信息传递后, 很自然的想到, 能不能 就像python socket一样通过改一下host地址进行两台电脑间的信息传递呢? 很遗憾, 没有这么简单, 尝试过后你会看到如 socket error occurred 的报错. 这是因为用户guest并不允许localhost以外的host.

为了解决这个问题, 我们需要做两件事:
1. 创建一个用户
2. 为用户提供访问vhost的权利

创建用户

rabbitmqctl add_user [username] [password]
如:   rabbitmqctl add_user hello 123456
  • 1
  • 2

为用户提供访问vhost的权利

rabbitmqctl set_permissions -p / [username] ".*" ".*" ".*"
如: rabbitmqctl set_permissions -p / hello ".*" ".*" ".*"
  • 1
  • 2

这样一来就可进行电脑间的信息通信啦! 一下为简单例子

send.cpp

#include <SimpleAmqpClient/SimpleAmqpClient.h>
#include <iostream>
#include <string>
using namespace std;
int main() {
  string queue = "hello";
  AmqpClient::Channel::ptr_t channel = AmqpClient::Channel::Create("192.168.199.229", 5672, "hello", "123456");  //host即为跑recv.cpp代码的电脑的ip地址
                          // 在linux下可通过指令ifconfig查看
  channel->DeclareQueue(queue, false, true, false, false);
  string str = "hello!";
 channel->BasicPublish("", queue, AmqpClient::BasicMessage::Create(str));
  cout << "sent hello";
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

recv.cpp

#include <SimpleAmqpClient/SimpleAmqpClient.h>
#include <iostream>
#include <string>
using namespace std;
int main() {
  while(1) {
    string queue = "hello";
    AmqpClient::Channel::ptr_t channel = AmqpClient::Channel::Create("192.168.199.229", 5672, "hello", "123456");
    channel->DeclareQueue(queue, false, true, false, false);
    AmqpClient::Envelope::ptr_t envelope;
    channel->BasicConsume(queue, "", true, true, false);
    bool success = channel->BasicConsumeMessage(envelope, -1);
    string buffer = envelope->Message()->Body();
    cout << buffer << endl;    
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

在一台电脑运行recv.cpp, 在另一台电脑运行send.cpp, 就可以在第一台电脑看到hello啦!
这样就实现了简单的电脑间通信!
编译命令还要加 -lSimpleAmqpClient参数

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/558149
推荐阅读
相关标签
  

闽ICP备14008679号