// 定义一个服务接口
class MyService {
public:
virtual void Publish(const std::string& message) = 0;
};
// 实现服务接口
class MyServiceImpl : public MyService {
public:
void Publish(const std::string& message) override {
// 将消息发布给所有订阅者
for (auto& client : clients_) {
someip::Message notification;
notification.SetMessageType(someip::MessageType::Notification);
notification.SetServiceID(0x1234);
notification.SetInstanceID(0x5678);
notification.SetMethodID(0x0001);
std::vector<uint8_t> data(message.begin(), message.end());
notification.SetPayload(data);
client->Send(notification);
}
}
// 添加一个订阅者
void AddSubscriber(std::shared_ptr<someip::Client> client) {
clients_.push_back(client);
}
private:
std::vector<std::shared_ptr<someip::Client>> clients_;
};
int main() {
// 创建一个服务实现对象和一个服务发布对象
MyServiceImpl serviceImpl;
someip::Server someipServer;
someipServer.RegisterService(0x1234, 0x5678, serviceImpl);
// 创建一个服务订阅者对象
someip::TCPConnection tcpConnection;
tcpConnection.Connect("127.0.0.1", 12345);
someip::Client someipClient(tcpConnection);
someipClient.Subscribe(0x1234, 0x5678);
// 将订阅者添加到服务实现对象中
serviceImpl.AddSubscriber(std::make_shared<someip::Client>(someipClient));
// 发布一个消息
serviceImpl.Publish("Hello, World!");
return 0;
}