diff --git a/Sources/TCPClient.swift b/Sources/TCPClient.swift index b498902..9489f16 100644 --- a/Sources/TCPClient.swift +++ b/Sources/TCPClient.swift @@ -32,6 +32,7 @@ import Foundation @_silgen_name("ytcpsocket_connect") private func c_ytcpsocket_connect(_ host:UnsafePointer,port:Int32,timeout:Int32) -> Int32 @_silgen_name("ytcpsocket_close") private func c_ytcpsocket_close(_ fd:Int32) -> Int32 +@_silgen_name("ytcpsocket_bytes_available") private func c_ytcpsocket_bytes_available(_ fd:Int32) -> Int32 @_silgen_name("ytcpsocket_send") private func c_ytcpsocket_send(_ fd:Int32,buff:UnsafePointer,len:Int32) -> Int32 @_silgen_name("ytcpsocket_pull") private func c_ytcpsocket_pull(_ fd:Int32,buff:UnsafePointer,len:Int32,timeout:Int32) -> Int32 @_silgen_name("ytcpsocket_listen") private func c_ytcpsocket_listen(_ address:UnsafePointer,port:Int32)->Int32 @@ -39,7 +40,6 @@ import Foundation @_silgen_name("ytcpsocket_port") private func c_ytcpsocket_port(_ fd:Int32) -> Int32 open class TCPClient: Socket { - /* * connect to server * return success or fail with message @@ -62,7 +62,7 @@ open class TCPClient: Socket { } } } - + /* * close socket * return success or fail with message @@ -136,6 +136,21 @@ open class TCPClient: Socket { return data } + + /* + * gets byte available for reading + */ + open func bytesAvailable() -> Int32? { + guard let fd:Int32 = self.fd else { return nil } + + let bytesAvailable = c_ytcpsocket_bytes_available(fd); + + if (bytesAvailable < 0) { + return nil + } + + return bytesAvailable + } } open class TCPServer: Socket { diff --git a/Sources/ytcpsocket.c b/Sources/ytcpsocket.c index e73b352..50ad313 100644 --- a/Sources/ytcpsocket.c +++ b/Sources/ytcpsocket.c @@ -44,6 +44,7 @@ #include #include #include +#include void ytcpsocket_set_block(int socket, int on) { int flags; @@ -130,6 +131,17 @@ int ytcpsocket_pull(int socketfd, char *data, int len, int timeout_sec) { return datalen; } +int ytcpsocket_bytes_available(int socketfd) { + int count; + int callResult = ioctl(socketfd, FIONREAD, &count); + + if (callResult < 0) { + return callResult; + } + + return count; +} + int ytcpsocket_send(int socketfd, const char *data, int len){ int byteswrite = 0; while (len - byteswrite > 0) {