Manage a server for notification system using PHP ratchets web sockets - php

Is it possible to achieve an online real-time notification system based (small scale)website which implements PHP ratchet websockets?
Locallly on my machine I start my PHP server using command prompt, but how could this be done for a hosted website?
As i will not be able start and maintain a server 24X7 for all remote clients, how would this actually work?(I dont have enough knowledge in this area)
Am i missing out on something?

Try the below code for notification feature:
<script>
if(typeof(EventSource) !== "undefined")
{
var source = new EventSource("demo_sse.php");
source.onmessage = function(event) {
notification(event.data);
};
}
</script>
And ofcourse you will need demo_sse.php which will be useful for fetching and storing data to the database.

Related

How to implement real time application pure

I am actually developing application for bank cash management.. It must be real-time... Once there is a change in db it must be sent to the client... I don't want to use long polling or ajax etc... (Because It puts load on the server by repeating requests)...
Cant use nodejs or other server related technology... (Not installed in server)... Question is that I want to develop server pure in php... Can anyone post code and give the details about it... Searched internet a lot but nothing there... Suggestions will be appreciated
[Edit]
I am putting my angularjs code for long polling here:
function dataCtrl($scope, $timeout, Data) {
$scope.data = [];
(function tick() {
$scope.data = Data.query(function(){
$timeout(tick, 1000);
});
})();
};
and I call tick function in the following code
$http.get('url').success(function(data, status, headers, config) {
data.response = data;
$('.serverStatus').text(data.response.message);
data.calls++;
$timeout(poller, 1000);
});
};
You must use sockets in your application... You can find Php socket library named Rachet over here
http://socketo.me/
There must be socket connection between users. So socket will listen until the data comes

Socket.io and PHP

Can someone please tell me if socket.io is only useful if the page your clients will use is a HTML page.
I want to create a node server that can push events to my existing PHP pages.
The pages are different and not suffixed with html.
All the examples I read use Chatroom examples with Index.html etc.
I simply want to know if what I want to do is even feasible.
Many thanks in advance.
When you write a php page the output is html. I hope that answers your question
PHP and socket.io work together. The only difference between doing it with html and with PHP is the way you link the two together (the common tutorial shows a way that only works with html, but there is another way that works with both html and php).
Try something like this (from a similar answer of mine, https://stackoverflow.com/a/25189436/3842050):
var socket = require('socket.io');
var express = require('express');
var http = require('http');
var app = express();
var server = http.createServer(app);
var io = socket.listen(server);
Then remove the app.use and app.get as they are no longer needed for how this is going to be done. Then add server.listen(8000); at the end of the server.js. For dependencies, use: <script src="//cdn.socket.io/socket.io-1.0.0.js"></script>. Then, to run your server, go to it in terminal and type node server.js. Then just connect to it with your client. Also, for events, in the server, use:
io.on('connection', function (client) {
client.on('someEvent', function(someVariables){
//Do something with someVariables when the client emits 'someEvent'
io.emit('anEventToClients', someData);
});
client.on('anotherEvent', function(someMoreVariables){
//Do more things with someMoreVariables when the client emits 'anotherEvent'
io.emit('anotherEventToClients', someMoreData);
});
});
And in your client code:
socket.emit('someEvent', variables);
socket.on('anEventToClients', function(something){
//Code when anEventToClient is emitted from the server
});

phonegap/cordova PayPal intergration

I'm trying to integrate PayPal payments within my Phonegap app. I can't see a cross platform way to do it.
I can only see OS specific plugins which I can't use in Phonegap build. Is there a way of integrating it using the childbrowser? Also, I failed to find a plugin for Blackberry.
Note: I use Phonegap build, so I prefer a plugin-less solution.
what you can do is the in app browser to connect to a php driven page online and there do your paypal stuff.
http://docs.phonegap.com/en/2.3.0/cordova_inappbrowser_inappbrowser.md.html
function onDeviceReady() {
var ref = window.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstart', function() { alert('start: ' + event.url); });
ref.addEventListener('loadstop', function() { alert('stop: ' + event.url); });
ref.addEventListener('exit', function() { alert(event.type); });
}
Remember to white list the url that you will be using within phonegap else you will not to be able to make a connection.
On the php side write your own restfull api to handle the processing of the payments try to minimize the data sent to and from the api also try to use a secure connection if possible.
paypal examples can be found here:
https://www.x.com/developers/paypal/documentation-tools/paypal-code-samples
its a solution but i do advise to use plugins for every platform, with those you can better guarantee safety, less bugs and less development time.

Loading pages with dynamic content

I've been working on a project for a couple of Minecraft servers that use Bukkit. I'm trying to create a web page that contains a dynamic map of the servers' worlds, as well as a real-time event update system, where a <div> is updated as events happen on the server. To give a brief outline of how my system works, the Minecraft servers communicate events with a Node.js webserver over the same network via UDP packets, and the Node.js webserver uses these packets to build JavaScript objects containing the event info. The objects are then stored, and passed to Jade whenever the page is requested. Jade takes care of the templating.
What I want to do is update this page dynamically, so that the user doesn't have to refresh the entire page to update the list of events. What I'm trying to implement is something like the Facebook ticker, which updates every time a Facebook friend does something like posting a status, commenting on a post, or 'liking' a post.
In reading this question on SO, I've concluded that I need to use long polling in a PHP script, but I'm not sure of how to integrate PHP with a webserver written almost entirely in Node.js. How could I go about doing this?
EDIT:
I've run into a problem in the clientside code.
This is the script block:
script(src='/scripts/jadeTemplate.js')
script(src='/socket.io/socket.io.js')
script(type='text/javascript')
var socket = io.connect();
socket.on('obj', function(obj) {
var newsItem = document.createElement("item");
jade.render(newsItem, 'objTemplate', { object: obj });
$('#newsfeed').prepend(newsItem);
console.log(obj);
alert(obj);
});
And this is objTemplate.jade:
p #{object}
// That's it.
When the alert() and console.log() are placed at the top of the script, it alerts and logs, but at the bottom, they don't execute (hence, I think it's a problem with either the creation of newsItem, the jade.render(), or the prepend.
If I need to provide any more snippets or files let me know. I'm still tinkering, so I might solve it on my own, but unless I update, I still need help. :)
I'd skip PHP and take a look at socket.io. It uses websockets when possible, but it will fall back to long-polling when necessary, and the client side library is very easy to use.
Whenever your node.js server has a new object ready to go, it will push it to all connected browsers. Use ClientJade to render the object using your template (you may have to break out the relevant part of the main template into its own file), then prepend the generated dom element to your feed.
First, if it isn't this way already, you'll need to break out the relevant part of your jade template into its own file. Call it objTemplate.jade. Then use ClientJade to create a compiled template that can be run in the browser: clientjade objTemplate.jade > jadeTemplate.js. Put jadeTemplate.js in your public js directory.
In your node.js app, you'll have something like this (pseudo-codey):
var io = require('socket.io').listen(httpServer);
listenForUDPPackets(function(obj) {
saveObjSomewhere(obj);
io.sockets.emit('obj', obj);
});
Then on the client, something like this:
<script src="/js/jadeTemplate.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect();
socket.on('obj', function(obj) {
var newsItem = document.createElement();
jade.render(newsItem, 'objTemplate', obj);
$('#newsFeed').prepend(newsItem);
});
</script>

HTML5 game <-> server

I have:
PHP Socket Server
PHP Pages to handle communication with server & db
Client .php page, which uses javascript/canvas to display & interact with a game.
What I want is for the user to connect and authenticate using the PHP pages which will initiate a socket connection to the server. Based on the information from that socket some chat info and events might be triggered to load data into client php page.
What is the right way to handle this. In all instances that I've ajax in before, the user triggers the event, not the server and javascript waits around for the php page's response.
What piece of php code from the php socket lets me send messages to the canvas elements?
Here's an example as the above is probably not very illuminating:
IE:
PHP reads off of its socket connection {"name":"msg","from":"user1","time":12345,"msg","hello world"}
At this point what does PHP do?** So that ...
The client has a div with "id='Incoming'"
I want to launch the following javascript:
function handleMessage(msgObj) {
var cText = document.getElementById("Incoming").innerHTML;
cText += "(" + msgObj.time + ")" + msgObj.from + " says: " + msgObj.msg +"<br/>";
document.getElementById("Incoming").innerHTML = cText;
}
I guess I'm trying to figure out how a client's web page is supposed to talk back to the php sockets...
Is this possible or do I need to make a client in flash, java, etc?
You send stuff from client to server when you've got data to send (e.g. user submits a button) typically via an event handler. The websocket also fires event when it receives data from the server (socket.onmessage). Simples.
ws.onmessage=function (evt) { handleMessage(evt.data); };
(or just change your handleMessage function body to use msgObj.data as the text value)
What piece of php code from the php socket lets me send messages to the canvas elements?
What websocket implementation are you using? They all have different APIs (NB a websocket is not the same thing as a network socket)
You should use Comet:
http://en.wikipedia.org/wiki/Comet_(programming)
AJAX is much better and also asynchronous
http://www.ape-project.org/
http://www.stream-hub.com/
...
http://cometdaily.com/maturity.html
or use HTML5 WebSockets

Categories