React Native Parse LiveQuery error on socket - sockets

I am having trouble connecting to the LiveQuery server that I setup on the server side of my React Native project. I followed the instructions on the site verbatim, but can only manage to get 'error on socket' when I connect with numerous attempts by the server to reconnect.
Here is my server setup:
liveQuery: {
classNames: ['BekonRequest'],
}
var port = 1337;
server.listen(port, function() {
console.log('parse-server running on port ' + port); });
var parseLiveQueryServer = ParseServer.createLiveQueryServer(server);
server.listen(port, function() {
console.log('parse-server running on port ' + port);
});
var parseLiveQueryServer = ParseServer.createLiveQueryServer(server);
And my client side code:
let requestQuery = new Parse.Query('BekonRequest');
requestQuery.equalTo("username", "broncos#nfl.com");
let subscription = requestQuery.subscribe();
subscription.on('create', (requests) => {
console.log(requests);
});
Can anyone see why I am not able to connect successfully?

Related

AEDES SERVER DOES NOT CONNECT TO CLIENT

I want to make a simple client server example with visual studio code. For my mqtt client instance, mosca didn't work. So I created a server with aedes. However, it is not possible to connect to client.js at the moment. I'm sure it's missing on the server side, but I'm not sure how to fix it. I'm very new to this. my codes are below.
Server;
const aedes = require('aedes')()
const server = require('net').createServer(aedes.handle)
const httpServer = require('http').createServer()
const ws = require('websocket-stream')
const port = 1883
const wsPort = 3000
server.listen(port, function () {
console.log('server started and listening on port ', port)
})
ws.createServer({ server: httpServer }, aedes.handle)
httpServer.listen(wsPort, function () {
console.log('websocket server listening on port ', wsPort)
})
Client;
var mqtt = require('mqtt');
var client = mqtt.connect('mqtt://192.168.43.40:1883');
client.subscribe('new-user');
client.on('connect', function() {
console.log('connected!');
client.publish('new-user', 'Cansu-' + Math.ceil(Math.random() * 10));
});
client.on('message', function(topic, message) {
console.log(topic, ' : ', message.toString());
client.end();
});
Thank You!!!

How can I connect WebSocket listening to one port to Net socket listening to another, using NodeJS?

This is the approach I tried but not working. I can forward the incoming messages from the WebSocket connection to the NetSocket, but only the first one received by NetSocket arrives to the client behind the WebSocket.
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
const NetSocket = require('net');
const net = new NetSocket.Socket();
// Web socket
wss.on('connection', function connection(ws) {
console.log((new Date()) + ' Remote connection accepted ' + ws.remoteAddress);
ws.on('message', function incoming(message) {
console.log('Received from remote: %s', message);
net.write(message)
});
ws.on('close', function(){
console.log((new Date()) + ' Remote connection closed');
});
});
// Net socket
net.connect(8745, '127.0.0.1', function() {
console.log((new Date()) + ' Local connection accepted');
});
net.on('data', function(data) {
console.log('Received from local: ' + data);
// Iterate the connected devices to send the broadcast
wss.clients.forEach(function each(c) {
if (c.readyState === WebSocket.OPEN) {
c.send(data);
}
});
});
net.on('close', function() {
console.log('Local connection closed');
});
After a new research I noticed that the problem was in my swift code.
private func setReceiveHandler() {
webSocketTask.receive { result in
defer { self.setReceiveHandler() } // I was missing this line
do {
let message = try result.get()
switch message {
case let .string(text):
print("Received text message: \(text)")
case let .data(data):
So, just adding defer { self.setReceiveHandler() } to my function, it started to work.
Note the defer statement at the start of the receive handler. It calls self.setReceiveHandler() to reset the receive handler on the socket connection to allow it to receive the next message. Currently, the receive handler you set on a socket connection is only called once, rather than every time a message is received. By using a defer statement, you make sure that self.setReceiveHandler is always called before exiting the scope of the receive handler, which makes sure that you always receive the next message from your socket connection.
I've got the information from:
https://www.donnywals.com/real-time-data-exchange-using-web-sockets-in-ios-13/

iPhone doesn't connect to the web socket but the simulator does

Physical devices cannot connect to my web socket. I tried it with 3 different phone and with different networks. It works fine with my simulators though. I am not getting an error message apart from the standard "Cannot connect to the server" from socket.io on the client.
I don't know if this is a valid indicator but I also tried using https://www.websocket.org/ with the following parameter:
wss://converzone.htl-perg.ac.at:5134
I am getting a "ERROR: undefined DISCONNECTED" there.
I am using an ubuntu server which runs Ubuntu 16.04. The web socket is from socket.io and I am coding with Swift on the client and with Node.js on the server. This whole thing is running on my school's server.
// Here is an array of all connections to the server
var connections = {};
io.sockets.on('connection', newConnection);
function newConnection(socket) {
console.log(socket.id + " connected.");
socket.on('add-user', function(user) {
connections[user.id] = {
"socket": socket.id
};
});
socket.on('chat-message', function(message) {
console.log(message);
if (connections[message.receiver]) {
console.log("Send to: " + connections[message.receiver].socket);
//io.sockets.connected[connections[message.receiver].socket].emit("chat-message", message);
io.to(connections[message.receiver].socket).emit('chat-message', message);
} else {
console.log("Send push notification")
sendPushNotificationToIOS(message.senderName, message, message.deviceToken, message.sound)
}
});
//Removing the socket on disconnect
socket.on('disconnect', function() {
console.log("The client disconnected");
console.log("The new list of clients is: " + connections)
for (var id in connections) {
if (connections[id].socket === socket.id) {
delete connections[id];
break;
}
}
})
}
Please understand that this problem seems very weird to me. I have changed the AppTransferProtocol in my plist and changed the port from 3000 to 5134. Nothing changed. Tell me what code would seem relevant apart from the (minimal) server code.

"Unable to connect to the Parse API" using Parse Server on Heroku

I'm getting the error Failed to create new object, with error code: XMLHttpRequest failed: "Unable to connect to the Parse API" when i try to connect to Parse Server API. I deployed ParsePlatform/parse-server-example on Heroku. I can access to my app with a broswser with no problems.I get the error when trying to connect to Parse on Heroku with this code :
var $result=$('#results').html('Testing configuration.....');
Parse.initialize('<MY_APP_ID>', '<MY_JAVASRIPT_KEY>');
Parse.serverURL = '<MY_HEROKU_APP_NAME>.herokuapp.com/'
var ParseServerTest = Parse.Object.extend('ParseServerTest');
var _ParseServerTest = new ParseServerTest();
_ParseServerTest.set('key', 'value');
_ParseServerTest.save(null, {
success: function(_ParseServerTest) {
var txt = 'Yay, your server works! New object created with objectId: ' + _ParseServerTest.id;
$result.html('<div class="alert alert-success" role="alert">' + txt + '</div>');
},
error: function(_ParseServerTest, error) {
var txt = 'Bummer, Failed to create new object, with error code: ' + error.message;
$result.html('<div class="alert alert-danger" role="alert">' + txt + '</div>');
}
});
index.js
// Example express application adding the parse-server module to expose Parse
// compatible API routes.
var express = require('express');
var cors = require('cors');
var ParseServer = require('parse-server').ParseServer;
var path = require('path');
var databaseUri = process.env.DATABASE_URI || process.env.MONGODB_URI;
if (!databaseUri) {
console.log('DATABASE_URI not specified, falling back to localhost.');
}
var api = new ParseServer({
databaseURI: databaseUri || 'mongodb://localhost:27017/dev',
cloud: process.env.CLOUD_CODE_MAIN || __dirname + '/cloud/main.js',
appId: process.env.APP_ID || 'myAppId',
masterKey: process.env.MASTER_KEY || '', //Add your master key here. Keep it secret!
serverURL: process.env.SERVER_URL || 'https://localhost:1337/parse', // Don't forget to change to https if needed
liveQuery: {
classNames: ["Posts", "Comments"] // List of classes to support for query subscriptions
}
});
// Client-keys like the javascript key or the .NET key are not necessary with parse-server
// If you wish you require them, you can set them as options in the initialization above:
// javascriptKey, restAPIKey, dotNetKey, clientKey
var app = express();
app.use(cors());
// Serve static assets from the /public folder
app.use('/public', express.static(path.join(__dirname, '/public')));
// Serve the Parse API on the /parse URL prefix
var mountPath = process.env.PARSE_MOUNT || '/parse';
app.use(mountPath, api);
// Parse Server plays nicely with the rest of your web routes
app.get('/', function(req, res) {
res.status(200).send('I dream of being a website. Please star the parse-server repo on GitHub!');
});
// There will be a test page available on the /test path of your server url
// Remove this before launching your app
app.get('/test', function(req, res) {
res.sendFile(path.join(__dirname, '/public/test.html'));
});
var port = process.env.PORT || 1337;
var httpServer = require('http').createServer(app);
httpServer.listen(port, function() {
console.log('parse-server-example running on port ' + port + '.');
});
// This will enable the Live Query real-time server
ParseServer.createLiveQueryServer(httpServer);
Heroku config :
I followed this post : How can I host my own Parse Server on Heroku using MongoDB? except i didn't use the "Deploy to Eroku" button, i deployed it manually.
Thank you for your help.
Finally I found a way.
I first created another user in my mongo db and change it in Heroku. Try to connect with the same js code code jsfiddle but didn't work...
Then I tried with an android client, this link helped me a lot http://www.robpercival.co.uk/parse-server-on-heroku/
StarterApplication.java
public class StarterApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
// Enable Local Datastore.
Parse.enableLocalDatastore(this);
// Add your initialization code here
Parse.initialize(new Parse.Configuration.Builder(getApplicationContext())
.applicationId("BUTYcVjD7nFz4Le")
.clientKey("XgQaeDY8Bfvw2r8vKCW")
.server("https://xxxxx-xxxx-xxxxx.herokuapp.com/parse")
.build()
);
ParseUser.enableAutomaticUser();
ParseACL defaultACL = new ParseACL();
// Optionally enable public read access.
// defaultACL.setPublicReadAccess(true);
ParseACL.setDefaultACL(defaultACL, true);
}
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
ParseAnalytics.trackAppOpenedInBackground(getIntent());
ParseObject test = new ParseObject("Test");
test.put("username","pedro");
test.put("age",33);
test.saveInBackground(new SaveCallback() {
public void done(ParseException e) {
if (e == null) {
Log.i("Parse", "Save Succeeded");
} else {
Log.e("Parse", "Save Failed");
}
}
});
}
I really don't know what was the problem with my first user, can't connect with it. I never could connect with the js code... but anyway my goal was to connect with Android client so...

Net Module Nodester not Listening to Port

I have a basic node.js app that is designed to open up a connection between two clients and echo the input of one to the other.
var net = require("net");
console.log("Relay Started");
var id = 0;
var Socket = [];
relay = net.createServer(function(socket) {
socket.on('connect', function() {
console.log('Connected');
if(socket.id==null) {
socket.id = id;
Socket[id]=socket;
id++;
}
});
socket.on('data', function(data) {
data = data.toString()
if (socket.id==0) {
Socket[1].write(data);
} else if (socket.id==1) {
Socket[0].write(data);
}
console.log(socket);
console.log(data.toString());
});
})
relay.listen(process.env['app_port']||8080);
It works fine when run locally, however when I put it onto a Nodester development server, I am unable to connect by using telnet zapcs.nodester.com 18007 (it is hosted under the name zapcs, and the given port is 18007). The Relay Started is logged, but nothing after that, and no connection. Any ideas on why this would be?
~
you can not telnet zapcs.nodester.com 18007, you only can connect to zapcs.nodester.com:80 by http or websock, nodester will route your request to your app actual port (18007) on the host.
And check this: http://www.slideshare.net/cmatthieu/nodester-architecture-overview-roadmap-9382423