From dce8de73198cab0fe6a4b60b5953346927c580da Mon Sep 17 00:00:00 2001 From: Kn3cht Date: Sun, 27 Sep 2020 16:54:28 +0200 Subject: [PATCH] Add setTimeout methods --- Sources/UDPClient.swift | 11 +++++++++++ Sources/yudpsocket.c | 9 +++++++++ 2 files changed, 20 insertions(+) diff --git a/Sources/UDPClient.swift b/Sources/UDPClient.swift index a3c39f5..f76b44c 100644 --- a/Sources/UDPClient.swift +++ b/Sources/UDPClient.swift @@ -37,6 +37,8 @@ import Foundation @_silgen_name("yudpsocket_get_server_ip") func c_yudpsocket_get_server_ip(_ host:UnsafePointer,ip:UnsafePointer) -> Int32 @_silgen_name("yudpsocket_sentto") func c_yudpsocket_sentto(_ fd:Int32,buff:UnsafePointer,len:Int32,ip:UnsafePointer,port:Int32) -> Int32 @_silgen_name("enable_broadcast") func c_enable_broadcast(_ fd:Int32) +@_silgen_name("set_timeout") func c_set_timeout(_ fd:Int32, _ timeoutSec:Int32, _ timeoutUSec:Int32) + open class UDPClient: Socket { public override init(address: String, port: Int32) { @@ -94,6 +96,15 @@ open class UDPClient: Socket { c_enable_broadcast(fd) } + /* + * setTimeout + */ + open func setTimeout(_ timeoutSec:Int32, _ timeoutUSec:Int32) { + guard let fd: Int32 = self.fd else { return } + + c_set_timeout(fd, timeoutSec, timeoutUSec) + } + /* * * send nsdata diff --git a/Sources/yudpsocket.c b/Sources/yudpsocket.c index e59a725..3ec0d5a 100644 --- a/Sources/yudpsocket.c +++ b/Sources/yudpsocket.c @@ -109,6 +109,15 @@ void enable_broadcast(int socket_fd) { setsockopt(socket_fd, SOL_SOCKET, SO_BROADCAST, &reuseon, sizeof(reuseon)); } +//set receiving timeout +void set_timeout(int socket_fd, int timeout_sec, int timeout_usec) { + struct timeval timeval; + timeval.tv_sec = timeout_sec; + timeval.tv_usec = timeout_usec; + + setsockopt(socket_fd, SOL_SOCKET, SO_RCVTIMEO, &timeval, sizeof(timeval)); +} + int yudpsocket_get_server_ip(char *host, char *ip) { struct hostent *hp; struct sockaddr_in address;