From 7337ed34a603aa21ebbdadc9a7a816292d3b1785 Mon Sep 17 00:00:00 2001 From: tostc <46672880+tostc@users.noreply.github.com> Date: Tue, 5 May 2020 16:47:41 +0200 Subject: [PATCH] Added asynchronous udp receive function (#193) * Added asynchronous udp receive function * Remove receive_async and added low level recv, which is non-blocking. * Remove thread include * Moved unix include to IXNetSystem.h --- ixwebsocket/IXNetSystem.h | 1 + ixwebsocket/IXUdpSocket.cpp | 26 ++++++++++++++++++++++++++ ixwebsocket/IXUdpSocket.h | 5 ++++- 3 files changed, 31 insertions(+), 1 deletion(-) diff --git a/ixwebsocket/IXNetSystem.h b/ixwebsocket/IXNetSystem.h index ca7920af..c5a5735c 100644 --- a/ixwebsocket/IXNetSystem.h +++ b/ixwebsocket/IXNetSystem.h @@ -29,6 +29,7 @@ typedef unsigned long int nfds_t; #include #include #include +#include #endif namespace ix diff --git a/ixwebsocket/IXUdpSocket.cpp b/ixwebsocket/IXUdpSocket.cpp index e15e083a..f05a223e 100644 --- a/ixwebsocket/IXUdpSocket.cpp +++ b/ixwebsocket/IXUdpSocket.cpp @@ -44,6 +44,18 @@ namespace ix return err; } + bool UdpSocket::isWaitNeeded() + { + int err = getErrno(); + + if (err == EWOULDBLOCK || err == EAGAIN || err == EINPROGRESS) + { + return true; + } + + return false; + } + void UdpSocket::closeSocket(int fd) { #ifdef _WIN32 @@ -62,6 +74,13 @@ namespace ix return false; } +#ifdef _WIN32 + unsigned long nonblocking = 1; + ioctlsocket(sockfd, FIONBIO, &nonblocking); +#else + fcntl(_sockfd, F_SETFL, O_NONBLOCK); // make socket non blocking +#endif + memset(&_server, 0, sizeof(_server)); _server.sin_family = AF_INET; _server.sin_port = htons(port); @@ -93,4 +112,11 @@ namespace ix return (ssize_t)::sendto( _sockfd, buffer.data(), buffer.size(), 0, (struct sockaddr*) &_server, sizeof(_server)); } + + ssize_t UdpSocket::recvfrom(void* buffer, size_t length) + { + uint32_t add_len = sizeof(_server); + return (ssize_t)::recvfrom( + _sockfd, buffer, length, 0, (struct sockaddr*) &_server, &add_len); + } } // namespace ix diff --git a/ixwebsocket/IXUdpSocket.h b/ixwebsocket/IXUdpSocket.h index 26be0f7d..c609886a 100644 --- a/ixwebsocket/IXUdpSocket.h +++ b/ixwebsocket/IXUdpSocket.h @@ -18,7 +18,7 @@ typedef SSIZE_T ssize_t; #include "IXNetSystem.h" namespace ix -{ +{ class UdpSocket { public: @@ -28,9 +28,12 @@ namespace ix // Virtual methods bool init(const std::string& host, int port, std::string& errMsg); ssize_t sendto(const std::string& buffer); + ssize_t recvfrom(void* buffer, size_t length); + void close(); static int getErrno(); + static bool isWaitNeeded(); static void closeSocket(int fd); private: