Merge pull request #137 from willson556/master

Add bytesAvailable() method.
This commit is contained in:
运筹 2018-06-25 10:13:29 +08:00 committed by GitHub
commit 7cd6d8e846
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 29 additions and 2 deletions

View File

@ -32,6 +32,7 @@ import Foundation
@_silgen_name("ytcpsocket_connect") private func c_ytcpsocket_connect(_ host:UnsafePointer<Byte>,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<Byte>,len:Int32) -> Int32
@_silgen_name("ytcpsocket_pull") private func c_ytcpsocket_pull(_ fd:Int32,buff:UnsafePointer<Byte>,len:Int32,timeout:Int32) -> Int32
@_silgen_name("ytcpsocket_listen") private func c_ytcpsocket_listen(_ address:UnsafePointer<Int8>,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 {

View File

@ -44,6 +44,7 @@
#include <fcntl.h>
#include <signal.h>
#include <sys/select.h>
#include <sys/ioctl.h>
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) {