add network.__closeserver

This commit is contained in:
MihailRis 2024-11-27 16:14:20 +03:00
parent 1b04a2a61e
commit 847ef23092
3 changed files with 19 additions and 5 deletions

View File

@ -58,6 +58,14 @@ static int l_close(lua::State* L) {
return 0;
}
static int l_closeserver(lua::State* L) {
u64id_t id = lua::tointeger(L, 1);
if (auto server = engine->getNetwork().getServer(id)) {
server->close();
}
return 0;
}
static int l_send(lua::State* L) {
u64id_t id = lua::tointeger(L, 1);
auto connection = engine->getNetwork().getConnection(id);
@ -127,6 +135,7 @@ const luaL_Reg networklib[] = {
{"get", lua::wrap<l_get>},
{"get_binary", lua::wrap<l_get_binary>},
{"__open", lua::wrap<l_open>},
{"__closeserver", lua::wrap<l_closeserver>},
{"__connect", lua::wrap<l_connect>},
{"__close", lua::wrap<l_close>},
{"__send", lua::wrap<l_send>},

View File

@ -254,11 +254,7 @@ static std::string to_string(const sockaddr_in* addr) {
static std::string to_string(const addrinfo* addr) {
if (addr->ai_family == AF_INET) {
auto psai = reinterpret_cast<sockaddr_in*>(addr->ai_addr);
char ip[INET_ADDRSTRLEN];
if (inet_ntop(addr->ai_family, &(psai->sin_addr), ip, INET_ADDRSTRLEN)) {
return std::string(ip)+":"+std::to_string(psai->sin_port);
}
return to_string(reinterpret_cast<sockaddr_in*>(addr->ai_addr));
} else if (addr->ai_family == AF_INET6) {
auto psai = reinterpret_cast<sockaddr_in6*>(addr->ai_addr);
char ip[INET6_ADDRSTRLEN];
@ -548,6 +544,14 @@ Connection* Network::getConnection(u64id_t id) const {
return found->second.get();
}
TcpServer* Network::getServer(u64id_t id) const {
const auto& found = servers.find(id);
if (found == servers.end()) {
return nullptr;
}
return found->second.get();
}
u64id_t Network::connect(const std::string& address, int port, consumer<u64id_t> callback) {
u64id_t id = nextConnection++;
auto socket = SocketConnection::connect(address, port, [id, callback]() {

View File

@ -75,6 +75,7 @@ namespace network {
);
[[nodiscard]] Connection* getConnection(u64id_t id) const;
[[nodiscard]] TcpServer* getServer(u64id_t id) const;
u64id_t connect(const std::string& address, int port, consumer<u64id_t> callback);