Skip to content

Commit

Permalink
Merge pull request #137 from willson556/master
Browse files Browse the repository at this point in the history
Add bytesAvailable() method.
  • Loading branch information
pengyunchou authored Jun 25, 2018
2 parents ab16278 + 8f5cd72 commit 7cd6d8e
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
19 changes: 17 additions & 2 deletions Sources/TCPClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,14 @@ 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
@_silgen_name("ytcpsocket_accept") private func c_ytcpsocket_accept(_ onsocketfd:Int32,ip:UnsafePointer<Int8>,port:UnsafePointer<Int32>,timeout:Int32) -> Int32
@_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
Expand All @@ -62,7 +62,7 @@ open class TCPClient: Socket {
}
}
}

/*
* close socket
* return success or fail with message
Expand Down Expand Up @@ -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 {
Expand Down
12 changes: 12 additions & 0 deletions Sources/ytcpsocket.c
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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) {
Expand Down

0 comments on commit 7cd6d8e

Please sign in to comment.