add nng error code.

This commit is contained in:
amass 2024-11-10 20:20:34 +08:00
parent 090ea0803e
commit 3b04085b04
4 changed files with 68 additions and 2 deletions

View File

@ -0,0 +1,22 @@
#include "ErrorCode.h"
#include <nng/nng.h>
namespace Nng {
const char *ErrorCategory::name() const noexcept {
return "nng";
}
std::string ErrorCategory::message(int ev) const {
return nng_strerror(ev);
}
static const std::error_category &errorCategory() {
static ErrorCategory instance;
return instance;
}
std::error_code makeErrorCode(int code) {
return {code, errorCategory()};
}
} // namespace Nng

View File

@ -0,0 +1,16 @@
#ifndef __ERRORCODE_H__
#define __ERRORCODE_H__
#include <system_error>
namespace Nng {
class ErrorCategory : public std::error_category {
public:
const char *name() const noexcept final;
std::string message(int ev) const final;
};
std::error_code makeErrorCode(int code);
} // namespace Nng
#endif // __ERRORCODE_H__

18
Nng/Option.h Normal file
View File

@ -0,0 +1,18 @@
#ifndef __OPTION_H__
#define __OPTION_H__
#include <chrono>
#include <nng/nng.h>
namespace Nng {
template <typename T>
struct Option {
constexpr Option(const char *opt) : option(opt) {};
const char *option;
};
inline constexpr Option<std::chrono::milliseconds> RecvTimeout(NNG_OPT_RECVTIMEO);
} // namespace Nng
#endif // __OPTION_H__

View File

@ -2,6 +2,8 @@
#define __SOCKET_H__
#include "Buffer.h"
#include "ErrorCode.h"
#include "Option.h"
#include "Protocol.h"
#include <cassert>
#include <nng/nng.h>
@ -22,8 +24,11 @@ public:
nng_listen(m_socket, url.data(), nullptr, flags);
}
void dial(const std::string_view &url, int flags = 0) {
nng_dial(m_socket, url.data(), nullptr, flags);
void dial(const std::string_view &url, std::error_code &error, int flags = 0) {
int status = nng_dial(m_socket, url.data(), nullptr, flags);
if (status != 0) {
error = makeErrorCode(status);
}
}
void send(const void *data, size_t size, int flags = 0) {
@ -37,6 +42,11 @@ public:
return Buffer(data, size);
}
template <class T>
void setOption(const Option<T> &opt, const T &value) {
nng_socket_set_ms(m_socket, opt.option, value.count());
}
protected:
nng_socket m_socket = NNG_SOCKET_INITIALIZER;
};