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

Update Readme #46

Open
wants to merge 20 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Specifies intentionally untracked files to ignore when using Git
# http://git-scm.com/docs/gitignore

.idea/
.DS_Store
Thumbs.db
73 changes: 43 additions & 30 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,36 +1,36 @@
sockets-for-cordova
===================
This Cordova plugin provides JavaScript API, that allows you to communicate with server through TCP protocol.
This Cordova plugin provides JavaScript API, that allows you to communicate with the server through TCP protocol.

Currently we support these platforms: iOS, Android, WP8.
Currently, we support these platforms: iOS, Android, WP8.

You can also get information about this plugin from our blog post http://www.blocshop.cz/blog/?p=6

## Installation

Install this plugin simply by:

`cordova plugin add cz.blocshop.socketsforcordova`
`cordova plugin add cordova-plugin-socket-tcp`

or you can use GIT repository for most recent version:
for the Ionic Framework

`cordova plugin add https://github.com/blocshop/sockets-for-cordova`
`ionic cordova plugin add cordova-plugin-socket-tcp`

## Sample usage
Here is simple example of how to connect to remote server, consume data from it and close the connection.
Here is a simple example of how to connect to a remote server, consume data from it, and close the connection.

Create instance of Socket type:
Create an instance of Socket type:
```
var socket = new Socket();
```

Set data consumer, error and close handlers:
Set data consumer, error, and close handlers:
```
socket.onData = function(data) {
// invoked after new batch of data is received (typed array of bytes Uint8Array)
};
socket.onError = function(errorMessage) {
// invoked after error occurs during connection
// invoked after an error occurs during connection
};
socket.onClose = function(hasError) {
// invoked after connection close
Expand All @@ -42,14 +42,14 @@ socket.open(
"someremoteserver.com",
1234,
function() {
// invoked after successful opening of socket
// invoked after the successful opening of the socket
},
function(errorMessage) {
// invoked after unsuccessful opening of socket
// invoked after unsuccessful opening of the socket
});
```

Send "Hello world" to server:
Send "Hello world" to the server:
```
var dataString = "Hello world";
var data = new Uint8Array(dataString.length);
Expand All @@ -59,7 +59,7 @@ for (var i = 0; i < data.length; i++) {
socket.write(data);
```

Close the connection gracefully by sending FIN to server:
Close the connection gracefully by sending FIN to the server:
```
socket.shutdownWrite();
```
Expand All @@ -72,10 +72,10 @@ socket.close();
## API
### Event handlers
#### `onData: (data: Uint8Array) => void`
Invoked after new batch of data is received by the client. Data are represented as typed array of bytes (`Uint8Array`).
Invoked after a new batch of data is received by the client. Data are represented as a typed array of bytes (`Uint8Array`).

#### `onClose: (hasError: boolean) => void`
Invoked after connection close. Native resources are released after this handler is invoked. Parameter `hasError` indicates whether connection was closed as a result of some error.
Invoked after connection closed. Native resources are released after this handler is invoked. The parameter `hasError` indicates whether the connection was closed as a result of some error.

#### `onError: (message: string) => void`
Invoked when some error occurs during connection.
Expand All @@ -88,10 +88,10 @@ Provides state of the socket. It can have 4 values represented by `Socket.State`
- `Socket.State.OPENED`
- `Socket.State.CLOSING`

Initial state of socket is CLOSED. Invoking `open` method changes state to OPENING. If it's successfuly opened, it goes to OPENED state. If opening fails, it goes back to CLOSED. Socket goes to CLOSING state immediately after `close` method is called. When socket is closed (by the server or by calling close method), it goes to CLOSED state.
The initial state of the socket is CLOSED. Invoking `open` method changes the state to OPENING. If it's successfully opened, it goes to OPENED state. If the opening fails, it goes back to CLOSED. Socket goes to CLOSING state immediately after `close` method is called. When the socket is closed (by the server or by calling the close method), it goes to CLOSED state.

##### Example
Check if socket is connected:
Check if the socket is connected:
```
if (socket.state == Socket.State.OPENED) {
console.log("Socket is opened");
Expand All @@ -100,38 +100,38 @@ if (socket.state == Socket.State.OPENED) {

### Methods
#### `open(host, port, onSuccess?, onError?): void`
Establishes connection with the remote host.
Establishes a connection with the remote host.

| parameter | type | description |
| ----------- |-----------------------------|--------------|
| `host` | `string` | Remote host/ip address |
| `port` | `number` | Tcp port number |
| `onSuccess` | `() => void` | Success callback - called after successfull connection to the remote host. (optional)|
| `onSuccess` | `() => void` | Success callback - called after successful connection to the remote host. (optional)|
| `onError` | `(message: string) => void` | Error callback - called when some error occurs during connecting to the remote host. (optional)|

#### `write(data, onSuccess?, onError?): void`
Sends data to remote host.
Sends data to the remote host.

| parameter | type | description |
| ----------- |-----------------------------|--------------|
| `data` | `Uint8Array` | Typed array of bytes, that will be written to output stream. |
| `data` | `Uint8Array` | Typed array of bytes, that will be written to the output stream. |
| `onSuccess` | `() => void` | Success callback - called after data are successfully written to the output stream. (optional)|
| `onError` | `(message: string) => void` | Error callback - called when some error occurs during writing of data to the output stream. (optional)|
| `onError` | `(message: string) => void` | Error callback - called when some error occurs during the writing of data to the output stream. (optional)|

#### `shutdownWrite(onSuccess?, onError?): void`
Sends `FIN` to remote host and finishes data sending. You cannot call `write` method after you call `shutdownWrite`, otherwise `onError` callback (of `write` method) will be called.
Sends `FIN` to the remote host and finishes data sending. You cannot call `write` method after you call `shutdownWrite`, otherwise `onError` callback (of `write` method) will be called.

| parameter | type | description |
| ----------- |-----------------------------|--------------|
| `onSuccess` | `() => void` | Success callback - called after sending of data is finished. (optional)|
| `onError` | `(message: string) => void` | Error callback - called when some error occurs during this procedure. (optional)|

#### `close(onSuccess?, onError?): void`
Closes the connection. `onClose` event handler is called when connection is successfuly closed.
Closes the connection. `onClose` event handler is called when the connection is successfully closed.

| parameter | type | description |
| ----------- |-----------------------------|--------------|
| `onSuccess` | `() => void` | Success callback, called after connection is successfully closed. `onClose` event handler is called before that callback. (optional)|
| `onSuccess` | `() => void` | Success callback, called after the connection is successfully closed. `onClose` event handler is called before that callback. (optional)|
| `onError` | `(message: string) => void` | Error callback, called when some error occurs during this procedure. (optional)|

## BSD License
Expand All @@ -141,9 +141,9 @@ All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. All advertising materials mentioning features or use of this software must display the following acknowledgement: This product includes software developed by the Blocshop s.r.o..
1. Redistributions of source code must retain the above copyright notice, this list of conditions, and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions, and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. All advertising materials mentioning features or use of this software must display the following acknowledgment: This product includes software developed by the Blocshop s.r.o.
4. Neither the name of the Blocshop s.r.o. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY Blocshop s.r.o. ''AS IS'' AND ANY
Expand All @@ -152,7 +152,20 @@ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER, CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

## What's new
- 1.2.3 - fixed iOS socket closing crashes [iOS]
- 1.5.0 - added iOS open and write timeouts, changed js errors format [iOS]
- 1.5.1 - fixed cordova js bridge implementation [js]
- 1.5.2 - fixed iOS open timeout [iOS]
- 1.5.3 - added Android open and write timeouts [Android]
- 1.5.4 - fixed iOS closing sockets on open timeout [iOS]
- 1.6.0 - close old existing sockets on reopen by destination ports. Removed iOS trash sources [iOS, Android]
- 1.7.0 - added codes to error handlers [iOS, Android]
- 1.7.1 - error handler bugfixes [Android]

Appelian, 2015
27 changes: 27 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"name": "cordova-plugin-socket-tcp",
"version": "1.7.1",
"description": "This Cordova plugin provides JavaScript API, that allows you to communicate with server through TCP protocol. Currently we support these platforms: iOS, Android, WP8.",
"cordova": {
"platforms": [
"ios",
"android",
"wp8"
]
},
"repository": {
"type": "git",
"url": "https://github.com/kitolog/sockets-for-cordova"
},
"keywords": [
"cordova",
"sockets",
"tcp",
"network",
"cordova-ios",
"cordova-wp8",
"cordova-android"
],
"author": "blocshop",
"license": "Apache-2.0"
}
8 changes: 1 addition & 7 deletions plugin.xml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>

<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0" id="cz.blocshop.socketsforcordova" version="1.1.0">
<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0" xmlns:android="http://schemas.android.com/apk/res/android" id="cordova-plugin-socket-tcp" version="1.7.1">
<name>SocketsForCordova</name>
<description>
This Cordova plugin provides JavaScript API, that allows you to communicate with server through TCP protocol.
Expand Down Expand Up @@ -45,11 +45,8 @@

<header-file src="src/ios/SocketsForCordova/Classes/SocketAdapter.h" />
<source-file src="src/ios/SocketsForCordova/Classes/SocketAdapter.m" />

<!--<framework src="CoreGraphics.framework" />-->
</platform>


<!-- wp8 -->
<platform name="wp8">
<config-file target="config.xml" parent="/*">
Expand All @@ -65,7 +62,4 @@
<source-file src="src/wp8/src/SocketEvent.cs" target-dir="src" />
<source-file src="src/wp8/src/SocketStorage.cs" target-dir="src" />
</platform>



</plugin>
62 changes: 41 additions & 21 deletions socket.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ Socket.State[Socket.State.OPENING = 1] = "OPENING";
Socket.State[Socket.State.OPENED = 2] = "OPENED";
Socket.State[Socket.State.CLOSING = 3] = "CLOSING";

Socket.ErrorType = {};
Socket.ErrorType[Socket.ErrorType.GENERAL = 0] = "general";
Socket.ErrorType[Socket.ErrorType.OPEN_TIMEOUT = 1] = "openTimeout";
Socket.ErrorType[Socket.ErrorType.WRITE_TIMEOUT = 2] = "writeTimeout";

function Socket() {
this._state = Socket.State.CLOSED;
this.onData = null;
Expand All @@ -37,8 +42,10 @@ function Socket() {

Socket.prototype.open = function (host, port, success, error) {

success = success || function() { };
error = error || function() { };
success = success || function () {
};
error = error || function () {
};

if (!this._ensureState(Socket.State.CLOSED, error)) {
return;
Expand All @@ -64,7 +71,7 @@ Socket.prototype.open = function (host, port, success, error) {
_that.onData(new Uint8Array(payload.data));
break;
case "Error":
_that.onError(payload.errorMessage);
_that.onError(payload);
break;
default:
console.error("SocketsForCordova: Unknown event type " + payload.type + ", socket key: " + payload.socketKey);
Expand All @@ -80,19 +87,25 @@ Socket.prototype.open = function (host, port, success, error) {
window.document.addEventListener(SOCKET_EVENT, socketEventHandler);
success();
},
function(errorMessage) {
function (errorMessage) {
_that._state = Socket.State.CLOSED;
error(errorMessage);
},
CORDOVA_SERVICE_NAME,
"open",
[ this.socketKey, host, port ]);
[
this.socketKey,
host,
port
]);
};

Socket.prototype.write = function (data, success, error) {

success = success || function() { };
error = error || function() { };
success = success || function () {
};
error = error || function () {
};

if (!this._ensureState(Socket.State.OPENED, error)) {
return;
Expand All @@ -107,13 +120,18 @@ Socket.prototype.write = function (data, success, error) {
error,
CORDOVA_SERVICE_NAME,
"write",
[ this.socketKey, dataToWrite ]);
[
this.socketKey,
dataToWrite
]);
};

Socket.prototype.shutdownWrite = function (success, error) {

success = success || function() { };
error = error || function() { };
success = success || function () {
};
error = error || function () {
};

if (!this._ensureState(Socket.State.OPENED, error)) {
return;
Expand All @@ -124,13 +142,15 @@ Socket.prototype.shutdownWrite = function (success, error) {
error,
CORDOVA_SERVICE_NAME,
"shutdownWrite",
[ this.socketKey ]);
[this.socketKey]);
};

Socket.prototype.close = function (success, error) {

success = success || function() { };
error = error || function() { };
success = success || function () {
};
error = error || function () {
};

if (!this._ensureState(Socket.State.OPENED, error)) {
return;
Expand All @@ -143,21 +163,21 @@ Socket.prototype.close = function (success, error) {
error,
CORDOVA_SERVICE_NAME,
"close",
[ this.socketKey ]);
[this.socketKey]);
};

Object.defineProperty(Socket.prototype, "state", {
get: function () {
get : function () {
return this._state;
},
enumerable: true,
configurable: true
enumerable : true,
configurable : true
});

Socket.prototype._ensureState = function(requiredState, errorCallback) {
Socket.prototype._ensureState = function (requiredState, errorCallback) {
var state = this._state;
if (state != requiredState) {
window.setTimeout(function() {
window.setTimeout(function () {
errorCallback("Invalid operation for this socket state: " + Socket.State[state]);
});
return false;
Expand Down Expand Up @@ -206,8 +226,8 @@ if (navigator.userAgent.match(/iemobile/i)) {
},
CORDOVA_SERVICE_NAME,
"registerWPEventDispatcher",
[ ]);
[]);
});
}

module.exports = Socket;
module.exports = Socket;