Kylin/Nng/Socket.h

56 lines
1.2 KiB
C
Raw Normal View History

2024-10-29 21:51:37 +08:00
#ifndef __SOCKET_H__
#define __SOCKET_H__
#include "Buffer.h"
2024-11-10 20:20:34 +08:00
#include "ErrorCode.h"
#include "Option.h"
2024-10-29 21:51:37 +08:00
#include "Protocol.h"
#include <cassert>
#include <nng/nng.h>
#include <string_view>
namespace Nng {
class Socket {
friend class Listener;
public:
2024-10-29 23:13:33 +08:00
Socket(Protocol protocol);
2024-10-29 21:51:37 +08:00
~Socket();
2024-10-29 23:13:33 +08:00
int id() const;
2024-10-29 21:51:37 +08:00
void listen(const std::string_view &url, int flags = 0) {
nng_listen(m_socket, url.data(), nullptr, flags);
}
2024-11-10 20:20:34 +08:00
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);
}
2024-10-29 21:51:37 +08:00
}
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);
}
2024-11-10 20:20:34 +08:00
template <class T>
void setOption(const Option<T> &opt, const T &value) {
nng_socket_set_ms(m_socket, opt.option, value.count());
}
2024-10-29 21:51:37 +08:00
protected:
nng_socket m_socket = NNG_SOCKET_INITIALIZER;
};
}; // namespace Nng
#endif // __SOCKET_H__