ratchet with zmq on subdomain not connecting - sockets

I'm trying to run ratchet on sub domain.. i have create ratchet server as described in Ratchet push integration and uploaded it to subdomain.domain.com my subdomain is also on same server
my projects is in laravel which is on main domain.(www.domain.com)
here is my chatserver code which is on subdomain
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
$loop = React\EventLoop\Factory::create();
$pusher = new MyApp\Pusher;
//Listen for the web server to make a ZeroMQ push after an ajax request
$context = new React\ZMQ\Context($loop);
$pull = $context->getSocket(ZMQ::SOCKET_PULL);
$pull->bind('tcp://subdomain.domain.com:5555'); //Binding to 27.0.0.1 means the only client that can connect is itself
$pull->on('message', array($pusher, 'onBookingSeats'));
//Set up our WebSocket server for clients wanting real-time updates
$webSock = new React\Socket\Server($loop);
$webSock->Listen(80,'0.0.0.0'); // Binding to 0.0.0.0 means remotes can connect
$webSock = new Ratchet\Server\IoServer(
new Ratchet\Http\HttpServer(
new Ratchet\WebSocket\WsServer(
new Ratchet\Wamp\WampServer(
$pusher
)
)
),
$webSock
);
$loop->run();
?>
my controller code from where i am sending request to socket which is on www.domain.com
$context = new ZMQContext();
$socket = $context->getSocket(ZMQ::SOCKET_PUSH, 'my pusher');
$socket->connect("tcp://subdomain.domain.com:5555");
$socket->send(json_encode($seats));
return Redirect::to('booking/payment');
and recieving websocket request in js file on www.domain.com
var conn = new ab.Session('ws://rtime.ticketpk.com:80',
function() {
conn.subscribe('kittensCategory', function(topic, data) {
// This is where you would add the new article to the DOM (beyond the scope of this tutorial)
console.log('New article published to category "' + topic + '" : ' + data.title);
});
},
function() {
console.warn('WebSocket connection closed');
},
{'skipSubprotocolCheck': true}
);
i think i'm having problem in binding with websockets

Related

"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...

React Native Parse LiveQuery error on socket

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?

Nodejs - websocket-node module: How to make multi-client socket-server works?

I created a socket server using websocket module with this configuration taken from this example (with some changes):
var WebSocketServer = require('websocket').server;
var http = require('http');
var server = http.createServer(function(request, response) {
console.log((new Date()) + ' Received request for ' + request.url);
response.writeHead(404);
response.end();
});
server.listen(5050, function() {
console.log((new Date()) + ' Server is listening on port 5050');
});
wsServer = new WebSocketServer({
httpServer: server,
// You should not use autoAcceptConnections for production
// applications, as it defeats all standard cross-origin protection
// facilities built into the protocol and the browser. You should
// *always* verify the connection's origin and decide whether or not
// to accept it.
autoAcceptConnections: false
});
function originIsAllowed(origin) {
// put logic here to detect whether the specified origin is allowed.
return true;
}
wsServer.on('request', function(request) {
if (!originIsAllowed(request.origin)) {
// Make sure we only accept requests from an allowed origin
request.reject();
console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
return;
}
var connection = request.accept('echo-protocol', request.origin);
console.log((new Date()) + ' Connection accepted.');
connection.on('message', function(message) {
if (message.type === 'utf8') {
console.log('Received Message: ' + message.utf8Data);
connection.sendUTF(message.utf8Data);
}
else if (message.type === 'binary') {
console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
connection.sendBytes(message.binaryData);
}
});
connection.on('close', function(reasonCode, description) {
console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
});
});
I create my own client in html :
<html>
<head>
<script src='./js/jquery1-11-3-min.js'></script>
<script>
$(document).ready(function (){
buildwebsocket();
});
var ws;
function buildwebsocket(){
ws = new WebSocket("ws://192.168.0.96:5050",'echo-protocol');
ws.onopen = function(evt) { onOpen(evt) };
ws.onclose = function(evt) { onClose(evt) };
ws.onmessage = function(evt) { onMessage(evt) };
ws.onerror = function(evt) { onError(evt) };
}
function onOpen(ev){
//alert("konek men! mantap! :D");
$("#recmsg").append("connected!<br>");
}
function onClose(ev){
$("#recmsg").append("connection closed!<br>");
}
function onMessage(ev){
//alert("ada pesan datang!");
$("#recmsg").append(ev.data+"<br>");
}
function onError(ev){
$("#recmsg").append("connecting error!<br>");
}
function doSend(){
//writeToScreen("SENT: " + message);
var message = $("#pesan").val();
ws.send(message);
} function doClose(){
ws.close();
}
//function writeToScreen(message){
//var pre = document.createElement("p");
//pre.style.wordWrap = "break-word";
//pre.innerHTML = message;
//output.appendChild(pre);
//}
//window.addEventListener("load", init, false);
</script>
</head>
<body>
<button onclick='doClose()'>Close</button>
<textarea id='pesan'></textarea><br>
<button onclick='doSend()'>Kirim!</button>
<br>
received message
<div id='recmsg'>
</div>
</body>
</html>
The connection between client (first client) and the server was successfully established. I try to send messages from first client, then the server receives the message without any promblem, and then the message sent back to the first client, and the first client receives it. I can say the connection and the socket works well.
I try to establish another connection (second client), so I open the second client in another device. The connection is good. But, when I send messages from the first or the second client, the first client doesn't get the response but the second client gets it.
And if open the third client and then send a message, the first and the second client don't get the response. Only the last connected client receives the response from server, and there's no client receives any error messages.
Is it the cons of the module? or the server configuration must be changed/added?
Can I establish multi-client-supported-socket-server using this module?
You're not storing the connections on the server side. You're just setting them up on the server to communicate directly back and forth to the server. If you want messages going to the server to be sent back out to everyone, you need to set up the .on('message', ...) function for each connection on the server to have that behavior. To do this, you'll need to store the connections as they are created. Try this:
var WebSocketServer = require('websocket').server;
var http = require('http');
var server = http.createServer(function(request, response) {
console.log((new Date()) + ' Received request for ' + request.url);
response.writeHead(404);
response.end();
});
server.listen(5050, function() {
console.log((new Date()) + ' Server is listening on port 5050');
});
wsServer = new WebSocketServer({
httpServer: server,
// You should not use autoAcceptConnections for production
// applications, as it defeats all standard cross-origin protection
// facilities built into the protocol and the browser. You should
// *always* verify the connection's origin and decide whether or not
// to accept it.
autoAcceptConnections: false
});
function originIsAllowed(origin) {
// put logic here to detect whether the specified origin is allowed.
return true;
}
//create an array to hold your connections
var connections = [];
wsServer.on('request', function(request) {
if (!originIsAllowed(request.origin)) {
// Make sure we only accept requests from an allowed origin
request.reject();
console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
return;
}
var connection = request.accept('echo-protocol', request.origin);
//store the new connection in your array of connections
connections.push(connection);
console.log((new Date()) + ' Connection accepted.');
connection.on('message', function(message) {
if (message.type === 'utf8') {
console.log('Received Message: ' + message.utf8Data);
//send the received message to all of the
//connections in the connection array
for(var i = 0; i < connections.length; i++) {
connections[i].sendUTF(message.utf8Data);
}
}
else if (message.type === 'binary') {
console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
connection.sendBytes(message.binaryData);
}
});
connection.on('close', function(reasonCode, description) {
console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
});
});

Using WebSockets on Samsung Smart TV

My requirement is to have a listening socket in my Samsung Smart TV app, in order to receive events from a device in the same local network.
I've been searching the web for methods to do that and I came across terms like Node.js, Socket.io, websocket. Even though i understand these terms in terms of web development (I think), I am unable to picture a method to open a listening socket in my Samsung Smart Tv App.
Just for the sake of playing around I wrote a TCP Server code on iOS using GCD Async Sockets and thought of connecting it to the smart tv and send a welcome message.
This is the code on my smart tv -
//var wsUri = "wss://echo.websocket.org/";
var wsUri = "ws://192.168.1.116:9898/";
//var output;
var webSocketObj={};
webSocketObj.init = function()
{
//output = document.getElementById("output");
this.testWebSocket();
};
webSocketObj.testWebSocket = function()
{
websocket = new WebSocket(wsUri);
websocket.onopen = function(evt) { onOpen(evt); };
websocket.onclose = function(evt) { onClose(evt); };
websocket.onmessage = function(evt) { onMessage(evt); };
websocket.onerror = function(evt) { onError(evt); };
};
function onOpen(evt)
{
writeToScreen("CONNECTED");
doSend("WebSocket rocks");
}
function onClose(evt)
{
writeToScreen("DISCONNECTED");
}
function onMessage(evt)
{
writeToScreen('<span style="color: blue;">RESPONSE: ' + evt.data+'</span>');
websocket.close();
}
function onError(evt)
{
writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
}
function doSend(message)
{
writeToScreen("SENT: " + message);
websocket.send(message);
}
function writeToScreen(message)
{
/* var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);*/
alert('SOCKET HELPER SAYS : '+message);
}
I have a button and I'm calling webSocketObj.init() on the button click.
Logs of my didReadData of the server :
Client says : GET / HTTP/1.1
Log from SmartTv :
[JS ALERT]: Scenewebsocket.handleKeyDown(29443)
[JS ERROR]:
File: file://
Line No: 0
Error Detail:
[JS ALERT]: SOCKET HELPER SAYS : DISCONNECTED
ALSO I tried echoing the message back to the Smart Tv from the server. And this time i got the logs
Client says : GET / HTTP/1.1
Client says : Upgrade: WebSocket
Client says : Connection: Upgrade
Client says : Host: 192.168.1.116:9898
Client says : Origin: file://
Client says : Sec-WebSocket-Key1: 1504l73 8Ew/J 4 ,L7W6
Client says : Sec-WebSocket-Key2: TK2 81d A64Bo7 118 0
I know i'm doing something horribly wrong...what is it? Pls help.
Have you tried socket.io server and client libraries?
We have socket.io server on node.js, and TV can connect to it using socket.io-client library. On 2012 TV it uses websocket. On 2011 TV it uses XHR fallback.
You can use socket.io library to make it easier for yourself to use WebSockets.
You would include a web browser version of socket.io in the samsung tv like this:
<script src="http://*some ip address*/socket.io/socket.io.js"></script>
Where some ip address is the ip address of a nodejs server that you control.
On your server you would need to install NodeJS with the socket.io server version.

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