Kylin/Nng/Socket.h
2024-11-10 20:20:34 +08:00

56 lines
1.2 KiB
C++

#ifndef __SOCKET_H__
#define __SOCKET_H__
#include "Buffer.h"
#include "ErrorCode.h"
#include "Option.h"
#include "Protocol.h"
#include <cassert>
#include <nng/nng.h>
#include <string_view>
namespace Nng {
class Socket {
friend class Listener;
public:
Socket(Protocol protocol);
~Socket();
int id() const;
void listen(const std::string_view &url, int flags = 0) {
nng_listen(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) {
nng_send(m_socket, (void *)data, size, flags);
}
Buffer recv(int flags = 0) const {
void *data;
size_t size;
int r = nng_recv(m_socket, &data, &size, flags | NNG_FLAG_ALLOC);
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;
};
}; // namespace Nng
#endif // __SOCKET_H__