PhoneGap sockets-for-cordova quit app - ios

I have a PhoneGap application and I want to open a socket to a endpoint using sockets-for-cordova plugin:
var socket = new Socket();
socket.open(
"192.168.2.1",
80,
function () {
// invoked after successful opening of socket
console.log("connection");
$scope.$apply();
},
function (errorMessage) {
// invoked after unsuccessful opening of socket
console.log("error");
$scope.$apply();
socket.shutdownWrite();
});
After I use this function to handle messages
socket.onData = function (data) {
// received message
}
On Android it works well, sending and receiving message, unfortunately on iOS it simply doesn't work, not receive any message at all or it close the socket itself.
I can see "connection" message, so I guess that the socket is created.

Related

Run socket Server in a ionic1 application

Here is the requirement:
Start a socket server in the app which will receive messages from another app running in the same device.
Here is the stack:
Ionic1/cordova
Angular1
cordova plugin: https://www.npmjs.com/package/cordova-plugin-chrome-apps-sockets-tcpserver
Using the chrome's tcpServer plugin, I ended this code:
angular.module('starter', ['ionic'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
var tcpServer = window.chrome && window.chrome.sockets &&
window.chrome.sockets.tcpServer;
if(tcpServer) {
console.log('LOG tcpServer present')
tcpServer.create({}, function (createInfo) {
var serverSocketId = createInfo.socketId;
console.log('LOG', 'serverSocketId', serverSocketId)
if (serverSocketId > 0) {
tcpServer.listen(serverSocketId, '0.0.0.0', 8080, 50, function(resultCode) {
console.log('LOG', 'listening', resultCode)
});
} else {
console.log('LOG', 'Unable to create socket');
}
});
} else {
console.log('LOG', 'missing chrome.sockets.tcpServer')
}
});
})
And the result of this code is:
LOG tcpServer present
LOG serverSocketId 0
LOG Unable to create socket
Given that I've no experience in ionic1/iOS:
Is this my option to create this socket server?
0 means that the create method failed. What could I be doing wrong here?
Do I need some special permission in iOS to perform those actions? (Similar to Android)
I couldn't find resources/examples to help me doing this. Where should I search?
Any help is appreciated

django-channels parse json/data sent via sockets

I have this javascript code that send data to channels
// Note that the path doesn't matter for routing; any WebSocket
// connection gets bumped over to WebSocket consumers
socket = new WebSocket("ws://" + window.location.host + "/chat/");
socket.onmessage = function(e) {
alert(e.data);
}
socket.onopen = function() {
socket.send({"test":"data"});
}
// Call onopen directly if socket is already open
if (socket.readyState == WebSocket.OPEN) socket.onopen();
I'm curios how from message I can get the json {"test":"data"}
here's the view
# Connected to websocket.connect
#channel_session
def ws_connect(message, key):
# Accept connection
message.reply_channel.send({"accept": True})
You implemented the connection callback, but did not implement what should happen when a message arrives the server endpoint. Add add message receive function:
def on_receive(message):
print('test received: {}'.format(message.content['test']))
Register the function in routing.py:
channel_routing = [
route("websocket.connect", ws_connect),
route("websocket.receive", on_receive),
]
The JSON message you send will be stored in message.content which is basically just a python dict.

Socket.io client not working properly

I have created chat application using following
Rails
Rabbitmq
nodejs ( with amqplib/callback_api and socket.io )
I have following code in server side
var amqp = require('amqplib/callback_api');
var amqpConn = null;
var app = require('http').createServer()
var io = require('socket.io')(app);
var fs = require('fs');
io.on('connection', function (socket) {
socket.emit('news/1', msg.content.toString());
// socket.disconnect()
});
client side
<%= javascript_include_tag "http://localhost:53597/socket.io/socket.io.js" %>
<script>
var socket = io('http://localhost:53597', {reconnect: true});
socket.on('connect', function () {
console.log('connected');
socket.on('news/1', function (msg) {
console.log('inside coming');
console.log(msg);
});
});
</script>
When I send message, message successfully pushed to queue and messages emitted to socket. The problem is I can get messages when only refresh page and messages are not deleted.
I can't understand what was wrong here ?
Eventually I fixed my issue, the problem is I have placed emit function inside connection event, so that I can get data when only connection established​, connection is established when page load that is the reason I get data when only page load.
I have the following code for emit data
io.sockets.emit('news/1', msg.content.toString());

Connection time out using local broker

I've downloaded Mosca (^1.1.2), MQTT (via npm) and Paho. When I create a simple broker as shown here: http://thejackalofjavascript.com/getting-started-mqtt/ (last 3 codes). It works all fine. My problem is when I try to implement client in the browser using Paho. with this code:
// Create a client instance
var client = new Paho.MQTT.Client('127.0.0.1', 4883, "clientId-1");
// set callback handlers
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
var options = {
//connection attempt timeout in seconds
timeout: 3,
//Gets Called if the connection has successfully been established
onSuccess: function () {
console.log("onConnect");
client.subscribe("testtopic/#");
},
//Gets Called if the connection could not be established
onFailure: function (message) {
console.log("Connection failed: " + message.errorMessage);
}
};
// connect the client
client.connect(options);
// called when the client connects
function onConnect() {
console.log("onConnect");
client.subscribe("testtopic/#");
}
// called when the client loses its connection
function onConnectionLost(responseObject) {
if (responseObject.errorCode !== 0) {
console.log("onConnectionLost:"+responseObject.errorMessage);
}
}
// called when a message arrives
function onMessageArrived(message) {
console.log(message.payload);
}
I always get this message: "Connection failed: AMQJSC0001E Connect timed out."
When I change '127.0.0.1' to a online broker, it works. So, I'm guessing my problem is with allowing ports in my broker.
Does anyone know how to solve this problem?

Exception ETIMEDOUT in node.js

I write application for iOS, which uses Socket.IO. Sometimes my server JS-script falls with this error:
events.js:85
throw er; // Unhandled 'error' event
^
Error: connect ETIMEDOUT
at exports._errnoException (util.js:746:11)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:983:19)
What I know is:
Script workes fine when I use only application for Android. That app uses Socket.IO for Android
Script workes fine when I use only web-client (yeap, with socket.IO)
Script startes to fall when I use iOS app.
Crash happens not always and not right away. Script falls after 5-10 minutes after connection and may crash, but may not.
So, I think the problem is in server library for socket.io, but exception fires only when iOS-client connecting.
How can I handle this exception?
UPDATE
There is problem was in the OAuth module on my node.js-server, which tried to check app token but had timeout to vk.com
I've edited vkapi module in my node.js server by adding "on" event for "https.get" function:
Was:
https.get(options, function(res) {
var apiResponse = new String();
res.setEncoding('utf8');
res.on('data', function(chunk) {
apiResponse += chunk;
});
res.on('end', function() {
var o = JSON.parse(apiResponse);
if (o.error) { self.emit('appServerTokenNotReady', o);
} else {
self.token = o.access_token;
self.emit('appServerTokenReady');
}
});
});
Now:
https.get(options, function(res) {
var apiResponse = new String();
res.setEncoding('utf8');
res.on('data', function(chunk) {
apiResponse += chunk;
});
res.on('end', function() {
var o = JSON.parse(apiResponse);
if (o.error) { self.emit('appServerTokenNotReady', o);
} else {
self.token = o.access_token;
self.emit('appServerTokenReady');
}
});
}).on('error', function(e) {
console.log('HTTPS error');
});
In general, you can handle these kinds of async errors by listening for the error event on whatever (e.g. request, connection, etc.) object.
The error event is special in that if there are currently no event handlers for it when it is emitted, the error will be thrown instead.

Resources