websocket php vs node js - javascript

Could somebody say what are the differences between "websocket php" http://www.php.net/manual/en/sockets.examples.php> and node.js? . I have chat with use websocket php but I don't know will better if this chat will move to node.js ?

Websockets are a transport built on TCP sockets. If you'll notice in the link you provided, the author recommends decoding data frames manually. There are projects that will help you with this, as #oberstet recommended (see also https://github.com/nicokaiser/php-websocket). #Kanaka has a great explanation for the difference between websockets and raw TCP sockets here.
Using node.js is certainly a smart, low-overhead way of rolling out a server for websocket connections. Another option is to use a realtime network. PubNub in particular has a blog post on how to write a chat app in 10 lines of code which is pretty accessible. Briefly, the code is:
Enter Chat and press enter
<div><input id=input placeholder=you-chat-here /></div>
Chat Output
<div id=box></div>
<script src=http://cdn.pubnub.com/pubnub.min.js></script>
<script>(function(){
var box = PUBNUB.$('box'), input = PUBNUB.$('input'), channel = 'chat';
PUBNUB.subscribe({
channel : channel,
callback : function(text) { box.innerHTML = (''+text).replace( /[<>]/g, '' ) + '<br>' + box.innerHTML }
});
PUBNUB.bind( 'keyup', input, function(e) {
(e.keyCode || e.charCode) === 13 && PUBNUB.publish({
channel : channel, message : input.value, x : (input.value='')
})
} )
})()</script>
A simple approach like this will allow you to cut out the server hosting and configuration entirely. Hope this helps!

This is like asking "what's the difference between PHP and HTTP". Node.js is a technology framework you write code in. WebSockets is a protocol which can be implemented using a technology framework. You can use Node.js to implement the server-side aspect of WebSockets.

Related

Windows Xbox JavaScript UWP APP get CPU/Memory Usage

Developing a JavaScript UWP app on Xbox and I would like to know how can I get CPU and memory usage information
I found this API, Windows.System.Diagnostics.ProcessCpuUsage
but the getReport method is not defined as claimed by Microsoft documentation
https://learn.microsoft.com/en-us/uwp/api/windows.system.diagnostics.processcpuusage
Any help would be greatly appreciated
With the Windows 10 Fall Creators Update 1709 (build 16299 and later) we have added a number of new diagnostics APIs to the UWP API surface to support scenarios like this. Please be sure to install and target the SDK version 16299 (or later). Here is a related blog post:
https://blogs.windows.com/buildingapps/2017/06/28/uwp-app-diagnostics/
I thought I'd add a quick code snippet here to reflect the JavaScript part of the question:
Keep in mind this is only here as a jump-start for anyone trying to get a memory report for your app as it's running from within JS. This is only example code and not terribly fault-tolerant.
Windows.System.AppDiagnosticInfo.requestInfoAsync().then((allProc) => {
let proc = allProc[0];
let allGroups = proc.getResourceGroups();
let procGroup = allGroups[0];
let memReport = procGroup.getMemoryReport();
console.log(memReport);
console.log(
` [${memReport.commitUsageLevel}] : commitUsageLevel \n` +
` [${memReport.commitUsageLimit}] : commitUsageLimit \n` +
` [${memReport.privateCommitUsage}] : privateCommitUsage \n` +
` [${memReport.totalCommitUsage}] : totalCommitUsage \n`
)
});

Kurento datachannel creation and management

I'm developing a WebRTC application based in node.js and Kurento and I want to implement a chat using datachannels.
I've seen the browser javascript version and I want to integrate it in the one to one node.js example.
What I have done
1.- I've created both WebRTCEndpoints with datachannel capabilities like this: pipeline.create('WebRtcEndpoint', {useDataChannels: true}, function(error, calleeWebRtcEndpoint) {...}
2.- Then I've created a <textarea> with a <button> to send messages, and a <div> to view them.
So my question is, what servers I have to put when I create the datachannel in the client? This snippet is from the browser javascript datachannel tutorial but at the start of the file we can clearly see ICE servers are ignoring in the connection creation. Also, I don’t know how you manage them in the node.js tutorials, so I'm a bit lost here.
peerConnection = new RTCPeerConnection(servers, configuration);
channel = peerConnection.createDataChannel(getChannelName(), dataConstraints);
channel.onopen = onSendChannelStateChange;
channel.onclose = onSendChannelStateChange;
channel.onmessage = onMessage;`
Thanks for the help.
I've discovered what was I doing wrong and now the I can send messages by datachannels.
Basically what I've done is to add peerConnection option to the options object. Next that option object is passed to WebRtcPeerSendrecv connection method and it's done!
var options = {
peerConnection: peerConnection, //Must be passed as a field in options to make DataChannels work
localVideo : videoInput,
remoteVideo : videoOutput,
onicecandidate : onIceCandidate
}
webRtcPeer = kurentoUtils.WebRtcPeer.WebRtcPeerSendrecv(options, function(){...});

JS OAuth 2.0 on Windows Phone 8.1

So, I'm trying to create a Gitter client for Windows Phone and to do so I need to use Bearer OAuth on their API. This process seems to result in a redirection to a gitter webpage (to get access tokens) and then it redirects to a web page specififed by my application. However obviously an APP is not a web page, so how am I supposed to get the returned temporary access token to use the API?
I've read a little bit about using ms-app://<security identifier> but it's all very fuzzy and little to no information seems to be about using it without using c#, but that's not what I'm looking for.
Any help would be greatly appreciated!
EDIT I just noticed this has been asked here oAuth 2.0 in Windows Phone 8.1 but hasn't been awnsered. Sorry for the duplication.
Seems that it was under my nose the whole entire time!
You can use Windows.Security.Authentication.Web.WebAuthenticationBroker.authenticateAndContinue(startURI, endURI);
(docs are mainly c# but here: http://msdn.microsoft.com/en-us/library/dn631755.aspx)
i.e
var redirect_uri = 'ms-app://<sid>';
var client_id = '<client id>';
// testing
var requestUri = new Windows.Foundation.Uri(
'https://<site>/?client_id=' + client_id + '&redirect_uri=' + redirect_uri
);
Windows.Security.Authentication.Web.WebAuthenticationBroker.authenticateAndContinue(requestUri, Windows.Foundation.Uri(redirect_uri));
app.addEventListener("activated", function (args) {
if (args.detail.kind == activation.ActivationKind.webAuthenticationBrokerContinuation) {
//take oauth response and continue login process
console.log(args.detail.webAuthenticationResult);
}
//Handle normal activiation...(hidden)
});
source: http://blog.stevenedouard.com/andcontinue-methods-for-windows-universal-apps/

Call javascript function from windows service c#

I need to call a javascript function inside a chrome-window from a windows service written in c#.
The browser is entirely at my disposal so I can configuration is no problem.
For example, the windows service is a file checker, when a certain file is changed there has to popup a js alert.
-EDIT-
The following works fine for client to client communication (server-side code).
So when a specific event happens on the server I can display this on the client (I hoped commented would do that)
using System;
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR.Client;
using SignalR.Hosting.Self;
using SignalR.Hubs;
namespace Net.SignalR.SelfHost
{
class Program
{
static void Main(string[] args)
{
string url = "http://localhost:8081/";
var server = new Server(url);
server.MapHubs();
server.Start();
Console.WriteLine("SignalR server started at " + url);
Console.ReadLine();
// Clients[collection].flush("bericht: " + message + collection);
}
//public void PushMessage(string bericht)
//{
// var hubConnection = new HubConnection("http://localhost:8081/");
// var serverHub = hubConnection.CreateProxy("CollectionHub");
// serverHub.On("flush", message => System.Console.WriteLine(message));
// hubConnection.Start().Wait();
// serverHub.Invoke("Subscribe", "Product");
// string line = null;
// while ((line = bericht) != null)
// {
// serverHub.Invoke("Publish", line, "Product").Wait();
// }
// System.Console.Read();
//}
public class CollectionHub : Hub
{
public void Subscribe(string collectionName)
{
Groups.Add(Context.ConnectionId, collectionName);
Console.WriteLine("Subscribed to: " + collectionName);
//serverHub.Invoke("Publish", "dit is een eerste test", "Product").Wait();
}
public Task Unsubscribe(string collectionName)
{
return Clients[collectionName].leave(Context.ConnectionId);
}
public void Publish(string message, string collection)
{
Clients[collection].flush("bericht: " + message + collection);
}
}
}
}
Sounds like you are describing SignalR.
What is ASP.NET SignalR?
ASP.NET SignalR is a new library for ASP.NET
developers that makes it incredibly simple to add real-time web
functionality to your applications. What is "real-time web"
functionality? It's the ability to have your server-side code push
content to the connected clients as it happens, in real-time.
You may have heard of WebSockets, a new HTML5 API that enables
bi-directional communication between the browser and server. SignalR
will use WebSockets under the covers when it's available, and
gracefully fallback to other techniques and technologies when it
isn't, while your application code stays the same.
SignalR also provides a very simple, high-level API for doing server
to client RPC (call JavaScript functions in your clients' browsers
from server-side .NET code) in your ASP.NET application, as well as
adding useful hooks for connection management, e.g. connect/disconnect
events, grouping connections, authorization.
What can you do with ASP.NET SignalR?
SignalR can be used to add any
sort of "real-time" web functionality to your ASP.NET application.
While chat is often used as an example, you can do a whole lot more.
Any time a user refreshes a web page to see new data, or the page
implements Ajax long polling to retrieve new data, is candidate for
using SignalR.
What it basicly does, is giving you access to the client AND server side functions in both directions, a simple example of it's usage can be found on the asp.net website which will give you a good idea on how to use it and what it's capable of doing.
You want to be using something like signal IR to do that, its what its designed for, essentially you are describing real time functionality;
Signal IR can be found here and has a great section on javascript in its wiki
In particular you probably want to take a look at Hubs

PHP WebSockets with Ratchet - example doesn't work

Here's some background first.
My aim is to use Ratchet WebSockets to create two-way client-server communication.
I have installed ratchet and accompanying software, as described here.
I have successfully created a Hello World application as described here.
Now I am trying to create Push functionality using this tutorial. I have copied the code, modifying it slightly (modifications noted in code comments below), installed the ZMQ library (latest version, added it to php.ini, show up in php -m - in short, it's installed correctly). But the WebSockets don't work.
I will give my testing process with real live links to my domain below, so you can check it yourself.
My push server is exactly the same as the one in their tutorial, with the IP changed to my server's IP. I run this through SSH and it seems to connect correctly.
My Pusher class is in the MyApp namespace, same code and same relative location as in their tutorial.
My post.php is slightly modified because there's no need to bother with MySQL queries:
$entryData = array( //hard-coded content of $entryData for simplicity
'cat' => "macka"
, 'title' => "naslov"
, 'article' => "tekst"
, 'when' => time()
);
// This is our new stuff
$context = new ZMQContext();
$socket = $context->getSocket(ZMQ::SOCKET_PUSH, 'my pusher');
$socket->connect("tcp://light-speed-games.com:5555"); //my domain, still using port 5555 as in their example
$socket->send(json_encode($entryData));
This file is located here.
My client.php is the same as theirs, except I had to add a little fix for IE to work with when.js. My problem is browser-independent and the same as it was before the fix was added.
<script>
window.define = function(factory) { //my addition
try{ delete window.define; } catch(e){ window.define = void 0; } // IE
window.when = factory();
};
window.define.amd = {};
</script>
<script src="/apps/scripts/when.js"></script>
<script src="http://autobahn.s3.amazonaws.com/js/autobahn.min.js"></script>
<script>
var conn = new ab.Session(
'ws://light-speed-games.com:8080' // The host (our Ratchet WebSocket server) to connect to
, function() { // Once the connection has been established
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() { // When the connection is closed
console.warn('WebSocket connection closed');
}
, { // Additional parameters, we're ignoring the WAMP sub-protocol for older browsers
'skipSubprotocolCheck': true
}
);
</script>
This file is located here.
In theory, what should happen is this (for example): I open client.php in Chrome with console switched on; then I open post.php in Firefox; Chrome's console should show the message 'New article published...' etc (from the conn.subscribe function in client.php). However, when I do this, nothing happens. The connection remains open (doesn't show the 'connection closed' error until I switch off push-server.php through SSH). The console remains empty.
I think that's all the relevant info from the last couple of days, a large portion of which I've spent on trying to figure this out. However, I've been unable to even make sure if the problem is with the code or with some server configuration setting I may be unaware of. So, I come to you hoping someone will point me in the right direction.
Important edit
I'm pretty sure the problem is with the Autobahn.js method conn.subscribe not working properly. The connection is being established. When I change the code to:
function() { // Once the connection has been established
console.log('Connection established');
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);
});
}
Then Connection established is shown in the console correctly. So I believe we need to troubleshoot the subscribe method. If someone can explain to me how it works, and what exactly "topic" and "data" are supposed to be, it would be of great help. The Autobahn documentation uses a URL as an argument for this method (see here).
Your client is looking for an article in kittensCategory, but you are sending category macka. Try this:
$entryData = array(
'cat' => "kittensCategory",
'title' => "naslov",
'article' => "tekst",
'when' => time()
);
Is it correct to see your host light-speed-games.com on port 8080 is not functioning? If not, I would suggest to fix this as it is likely its causing your issues.

Categories

Resources