Skip to content

Commit 7cd6d8e

Browse files
authored
Merge pull request #137 from willson556/master
Add bytesAvailable() method.
2 parents ab16278 + 8f5cd72 commit 7cd6d8e

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

Sources/TCPClient.swift

+17-2
Original file line numberDiff line numberDiff line change
@@ -32,14 +32,14 @@ import Foundation
3232

3333
@_silgen_name("ytcpsocket_connect") private func c_ytcpsocket_connect(_ host:UnsafePointer<Byte>,port:Int32,timeout:Int32) -> Int32
3434
@_silgen_name("ytcpsocket_close") private func c_ytcpsocket_close(_ fd:Int32) -> Int32
35+
@_silgen_name("ytcpsocket_bytes_available") private func c_ytcpsocket_bytes_available(_ fd:Int32) -> Int32
3536
@_silgen_name("ytcpsocket_send") private func c_ytcpsocket_send(_ fd:Int32,buff:UnsafePointer<Byte>,len:Int32) -> Int32
3637
@_silgen_name("ytcpsocket_pull") private func c_ytcpsocket_pull(_ fd:Int32,buff:UnsafePointer<Byte>,len:Int32,timeout:Int32) -> Int32
3738
@_silgen_name("ytcpsocket_listen") private func c_ytcpsocket_listen(_ address:UnsafePointer<Int8>,port:Int32)->Int32
3839
@_silgen_name("ytcpsocket_accept") private func c_ytcpsocket_accept(_ onsocketfd:Int32,ip:UnsafePointer<Int8>,port:UnsafePointer<Int32>,timeout:Int32) -> Int32
3940
@_silgen_name("ytcpsocket_port") private func c_ytcpsocket_port(_ fd:Int32) -> Int32
4041

4142
open class TCPClient: Socket {
42-
4343
/*
4444
* connect to server
4545
* return success or fail with message
@@ -62,7 +62,7 @@ open class TCPClient: Socket {
6262
}
6363
}
6464
}
65-
65+
6666
/*
6767
* close socket
6868
* return success or fail with message
@@ -136,6 +136,21 @@ open class TCPClient: Socket {
136136

137137
return data
138138
}
139+
140+
/*
141+
* gets byte available for reading
142+
*/
143+
open func bytesAvailable() -> Int32? {
144+
guard let fd:Int32 = self.fd else { return nil }
145+
146+
let bytesAvailable = c_ytcpsocket_bytes_available(fd);
147+
148+
if (bytesAvailable < 0) {
149+
return nil
150+
}
151+
152+
return bytesAvailable
153+
}
139154
}
140155

141156
open class TCPServer: Socket {

Sources/ytcpsocket.c

+12
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@
4444
#include <fcntl.h>
4545
#include <signal.h>
4646
#include <sys/select.h>
47+
#include <sys/ioctl.h>
4748

4849
void ytcpsocket_set_block(int socket, int on) {
4950
int flags;
@@ -130,6 +131,17 @@ int ytcpsocket_pull(int socketfd, char *data, int len, int timeout_sec) {
130131
return datalen;
131132
}
132133

134+
int ytcpsocket_bytes_available(int socketfd) {
135+
int count;
136+
int callResult = ioctl(socketfd, FIONREAD, &count);
137+
138+
if (callResult < 0) {
139+
return callResult;
140+
}
141+
142+
return count;
143+
}
144+
133145
int ytcpsocket_send(int socketfd, const char *data, int len){
134146
int byteswrite = 0;
135147
while (len - byteswrite > 0) {

0 commit comments

Comments
 (0)