Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Android and ios binary support #74

Open
wants to merge 14 commits into
base: master
Choose a base branch
from
29 changes: 26 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ The plugin creates a "Socket" object exposed on window.tlantic.plugins.socket. T
* connect: opens a socket connection;
* disconnect: closes a socket connection;
* disconnectAll: closes ALL opened connections;
* send: send data using a given connection;
* send: send text data using a given connection;
* sendBinary: send binary data using a given connection;
* isConnected: returns a boolean falg representing socket connectivity status;
* receive: callback used by plugin's native code. Can be override by a custom implementation.

Expand Down Expand Up @@ -90,7 +91,7 @@ window.tlantic.plugins.socket.connect(

### send (successCallback, errorCallback, connectionId, data)

Sends information and calls success callback if information was send and does not wait for any response. To check how to receive data, please see the item below.
Sends text information and calls success callback if information was sent and does not wait for any response. To check how to receive data, please see the item below.

Example:

Expand All @@ -108,7 +109,29 @@ window.tlantic.plugins.socket.send(
);
```

### isConnected (connectionId, successCallback, errorCallback)
### sendBinary (successCallback, errorCallback, connectionId, data)

Sends binary data and calls success callback if information was sent and does not wait for any response. To check how to receive data, please see the item below.

Binary data to be sent is passed in `data` which is a JSONArray, one integer element per byte.

Example:

```
window.tlantic.plugins.socket.sendBinary(
function () {
console.log('worked!');
},

function () {
console.log('failed!');
},
'192.168.2.5:18002',
[ 0x00, 0x01, 0x00, 0xFD ]
);
```

#### isConnected (connectionId, successCallback, errorCallback)

Returns a boolean value representing the connection status. True, if socket streams are opened and false case else.
Both values are supposed to be returned through successCallback. The error callback is called only when facing errors due the check process.
Expand Down
267 changes: 140 additions & 127 deletions src/android/Connection.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
Expand All @@ -11,135 +12,147 @@
/**
* @author viniciusl
*
* This class represents a socket connection, behaving like a thread to listen
* This class represents a socket connection, behaving like a thread to listen
* a TCP port and receive data
*/
public class Connection extends Thread {
private SocketPlugin hook;

private Socket callbackSocket;
private PrintWriter writer;
private BufferedReader reader;

private Boolean mustClose;
private String host;
private int port;


/**
* Creates a TCP socket connection object.
*
* @param pool Object containing "sendMessage" method to be called as a callback for data receive.
* @param host Target host for socket connection.
* @param port Target port for socket connection
*/
public Connection(SocketPlugin pool, String host, int port) {
super();
setDaemon(true);

this.mustClose = false;
this.host = host;
this.port = port;
this.hook = pool;
}


/**
* Returns socket connection state.
*
* @return true if socket connection is established or false case else.
*/
public boolean isConnected() {

boolean result = (
this.callbackSocket == null ? false :
this.callbackSocket.isConnected() &&
this.callbackSocket.isBound() &&
!this.callbackSocket.isClosed() &&
!this.callbackSocket.isInputShutdown() &&
!this.callbackSocket.isOutputShutdown());

// if everything apparently is fine, time to test the streams
if (result) {
try {
this.callbackSocket.getInputStream().available();
} catch (IOException e) {
// connection lost
result = false;
}
}

return result;
}

/**
* Closes socket connection.
*/
public void close() {
// closing connection
try {
//this.writer.close();
//this.reader.close();
callbackSocket.shutdownInput();
callbackSocket.shutdownOutput();
callbackSocket.close();
this.mustClose = true;
} catch (IOException e) {
e.printStackTrace();
}
}


/**
* Writes on socket output stream to send data to target host.
*
* @param data information to be sent
*/
public void write(String data) {
this.writer.println(data);
}



/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
public void run() {
String chunk = null;

// creating connection
try {
this.callbackSocket = new Socket(this.host, this.port);
this.writer = new PrintWriter(this.callbackSocket.getOutputStream(), true);
this.reader = new BufferedReader(new InputStreamReader(callbackSocket.getInputStream()));

// receiving data chunk
while(!this.mustClose){

try {

if (this.isConnected()) {
chunk = reader.readLine();

if (chunk != null) {
chunk = chunk.replaceAll("\"\"", "null");
System.out.print("## RECEIVED DATA: " + chunk);
hook.sendMessage(this.host, this.port, chunk);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}

} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

}
private SocketPlugin hook;

private Socket callbackSocket;
private PrintWriter writer;
private OutputStream outputStream;
private BufferedReader reader;

private Boolean mustClose;
private String host;
private int port;


/**
* Creates a TCP socket connection object.
*
* @param pool Object containing "sendMessage" method to be called as a callback for data receive.
* @param host Target host for socket connection.
* @param port Target port for socket connection
*/
public Connection(SocketPlugin pool, String host, int port) {
super();
setDaemon(true);

this.mustClose = false;
this.host = host;
this.port = port;
this.hook = pool;
}


/**
* Returns socket connection state.
*
* @return true if socket connection is established or false case else.
*/
public boolean isConnected() {

boolean result = (
this.callbackSocket == null ? false :
this.callbackSocket.isConnected() &&
this.callbackSocket.isBound() &&
!this.callbackSocket.isClosed() &&
!this.callbackSocket.isInputShutdown() &&
!this.callbackSocket.isOutputShutdown());

// if everything apparently is fine, time to test the streams
if (result) {
try {
this.callbackSocket.getInputStream().available();
} catch (IOException e) {
// connection lost
result = false;
}
}

return result;
}

/**
* Closes socket connection.
*/
public void close() {
// closing connection
try {
//this.writer.close();
//this.reader.close();
callbackSocket.shutdownInput();
callbackSocket.shutdownOutput();
callbackSocket.close();
this.mustClose = true;
} catch (IOException e) {
e.printStackTrace();
}
}


/**
* Writes on socket output stream to send data to target host.
*
* @param data information to be sent
*/
public void write(String data) {
this.writer.println(data);
}



/**
* Outputs to socket output stream to send binary data to target host.
*
* @param data information to be sent
*/
public void writeBinary(byte[] data) throws IOException {
this.outputStream.write(data);
}


/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
public void run() {
byte[] chunk = new byte[512];

// creating connection
try {
this.callbackSocket = new Socket(this.host, this.port);
this.writer = new PrintWriter(this.callbackSocket.getOutputStream(), true);
this.outputStream = this.callbackSocket.getOutputStream();
this.reader = new BufferedReader(new InputStreamReader(callbackSocket.getInputStream()));

// receiving data chunk
while(!this.mustClose){

try {

if (this.isConnected()) {
int bytesRead = callbackSocket.getInputStream().read(chunk);
byte[] line = new byte[bytesRead];
System.arraycopy(chunk, 0, line, 0, bytesRead);

if (bytesRead > 0) {
hook.sendMessage(this.host, this.port, line);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}

} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

}

}
Loading