赞
踩
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
)
当我们成功地在一台电脑上实现了两个终端之间的信息传递后, 很自然的想到, 能不能 就像python socket一样通过改一下host地址进行两台电脑间的信息传递呢? 很遗憾, 没有这么简单, 尝试过后你会看到如 socket error occurred 的报错. 这是因为用户guest并不允许localhost以外的host.
为了解决这个问题, 我们需要做两件事:
1. 创建一个用户
2. 为用户提供访问vhost的权利
创建用户
rabbitmqctl add_user [username] [password]
如: rabbitmqctl add_user hello 123456
为用户提供访问vhost的权利
rabbitmqctl set_permissions -p / [username] ".*" ".*" ".*"
如: rabbitmqctl set_permissions -p / hello ".*" ".*" ".*"
这样一来就可进行电脑间的信息通信啦! 一下为简单例子
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";
}
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;
}
}

在一台电脑运行recv.cpp, 在另一台电脑运行send.cpp, 就可以在第一台电脑看到hello啦!
这样就实现了简单的电脑间通信!
编译命令还要加 -lSimpleAmqpClient参数
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。