Dart How to code a simple web-socket echo app - websocket

I've been attempting to learn enough html, css, and Dart to create my first web page and all is going well, except that I do not understand how to create a simple page and a server side web-socket server that will just echo it back. The examples that I find tend to illustrate other Dart tools and either connect to echo server on the web or do other things that make their code not simple for a newbie.
I've tried to simplify Seth Ladd's example "dart-example-web-sockets-client" as the 'best' example. I can receive what is sent from the page, repackage it and think i'm sending it back but absolutely nothing happens on the web page. I start the page by clicking on the URL returned when the web-server is run from inside the Dart editor. Since the page is not, AFAIK, run in the debugger I'm hampered in diagnosing the error.
Here is simplified code from Seth's server:
void handleEchoWebSocket(WebSocket webSocket) {
log.info('New WebSocket connection');
// Listen for incoming data. We expect the data to be a JSON-encoded String.
webSocket
.map((string) => JSON.decode(string))
.listen((json) {
// The JSON object should contain a 'request' entry.
var request = json['request'];
switch (request) {
case 'search':
var input = json['input'];
log.info("Received request '$request' for '$input'");
var response = {
'response': request,
'input': input,
};
webSocket.add(JSON.encode(response)); // can't detect page receiving this.
log.info("Echoed request..$request $input"); // correct data
break;
default:
log.warning("Invalid request: '$request'");
}
}, onError: (error) {
log.warning('Bad WebSocket request');
});
}
This example took the user input using it as input to two search engines, packaged the results and returned them to the page for display creating new DOM elements on the fly.
I just need to be pointed to a simple example that will echo what is submitted.

Here is a simple websocket client/server echo example. Messages doesn't show in browser window, but they are printed in console window. You have to start server.dart and main.dart separately. Both processes print messages to their own console window.
Edit: I added an output div for displaying the message also in browser.
bin\ws_server.dart:
import "dart:convert";
import 'dart:io';
import 'package:route/server.dart' show Router;
void handleWebSocket(WebSocket webSocket) {
// Listen for incoming data. We expect the data to be a JSON-encoded String.
webSocket
.map((string)=> JSON.decode(string))
.listen((json) {
// The JSON object should contains a 'echo' entry.
var echo = json['echo'];
print("Message to be echoed: $echo");
var response='{"response": "$echo"}';
webSocket.add(response);
}, onError: (error) {
print('Bad WebSocket request');
});
}
void main() {
int port = 9223;
HttpServer.bind(InternetAddress.LOOPBACK_IP_V4, port).then((server) {
print("Search server is running on "
"'http://${server.address.address}:$port/'");
var router = new Router(server);
// The client will connect using a WebSocket. Upgrade requests to '/ws' and
// forward them to 'handleWebSocket'.
router.serve('/ws')
.transform(new WebSocketTransformer())
.listen(handleWebSocket);
});
}
web\index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Websocket echo</title>
</head>
<body>
<p>Websocket test</p>
<div id="output"></div>
<script type="application/dart" src="main.dart"></script>
</body>
</html>
web\main.dart:
library main;
import 'dart:async';
import 'dart:convert';
import 'dart:html';
class WebsocketService {
WebSocket webSocket;
WebsocketService() {
connect();
}
void connect() {
webSocket = new WebSocket('ws://127.0.0.1:9223/ws');
webSocket.onOpen.first.then((_) {
onConnected();
sendws("Hello websocket server");
webSocket.onClose.first.then((_) {
print("Connection disconnected to ${webSocket.url}");
onDisconnected();
});
});
webSocket.onError.first.then((_) {
print("Failed to connect to ${webSocket.url}. "
"Please run bin/server.dart and try again.");
onDisconnected();
});
}
void onConnected() {
webSocket.onMessage.listen((e) {
onMessage(e.data);
});
}
void onDisconnected() {
print("Disconnected, trying again in 3s");
new Timer(new Duration(seconds:3), (){
connect();
});
}
void onMessage(data) {
var json = JSON.decode(data);
var echoFromServer = json['response'];
print("Received message: $echoFromServer");
var output=querySelector('#output');
output.text="Received message: $echoFromServer";
new Timer(new Duration(seconds:3), (){ //Send a new message to server after 3s
String now = new DateTime.now().toString();
sendws("Time: $now");
});
}
void sendws(String msg){
var request = '{"echo": "$msg"}';
print("Send message to server: $request");
webSocket.send(request);
}
}
void main() {
WebsocketService ws=new WebsocketService();
}

Related

The ParseReact is not receiving data (error: this._subscriptions[name].dispose is not a function)

I am using parse as my app back-end, but I am unable to receive data with the observe() method, although I'm sure that react is properly connect with parse, because I can mutate data with the ParseReact.mutation.
import React from 'react';
import Parse from 'parse';
import ParseReact from 'parse-react';
const pinRegister = React.createClass({
mixins: [ParseReact.Mixin],
observe() {
return {
pins: (new Parse.Query('Pin'))
},
render() {
return {
<ul>
{this.data.pins.map(function(pin) {
return <li>{pin}</li>;
})}
</ul>
}
}
});
On the console I receive this message: "WebSocket connection to 'ws://mywsaddress:8080/parse' failed: Connection closed before receiving a handshake response" and the this.data.pins gets undefined,I checked the data in parse-dashboard and the Pin class has the properly data.
Edit: I add the liveQuery on my parse server, and the socket error stopped, but I'm still unable to receive data, on chrome's console I get this: Uncaught TypeError: this._subscriptions[name].dispose is not a function, and this problem comes from this peace of code from parse-react:
_unsubscribe: function _unsubscribe() {
for (var name in this._subscriptions) {
this._subscriptions[name].dispose();
}
this._subscriptions = {};
},
You are not included ParseReact.Mixin correctly. Replace "mixis" on "mixins".
mixins: [ParseReact.Mixin]

YouTube Data API: add a subscription

I'm using YouTube's V3 Data API to add a subscription to a channel. This occurs on a Wordpress installation.
I added Google APIs (for oauth) on Wordpress theme functions:
wp_enqueue_script( 'googleapi', 'https://apis.google.com/js/client.js?onload=googleApiClientReady', array(), '1.0.0', true );
I added in the same way the oauth javascript file, which is the first one here: https://developers.google.com/youtube/v3/code_samples/javascript.
Following this guide(https://developers.google.com/youtube/v3/docs/subscriptions/insert (Apps Script)), I extended the OAuth js with the addSubscription method.
Google Client API seems to be loaded and working as it calls correctly googleApiClientReady on the oauth javascript.
So, this is how the subscription is being inserted:
OAUTH JAVASCRIPT
... ... ...
// After the API loads
function handleAPILoaded() {
addSubscription();
}
function addSubscription() {
// Replace this channel ID with the channel ID you want to subscribe to
var channelId = 'this is filled with the channel ID';
var resource = {
snippet: {
resourceId: {
kind: 'youtube#channel',
channelId: channelId
}
}
};
try {
var response = YouTube.Subscriptions.insert(resource, 'snippet');
jQuery('#success').show();
} catch (e) {
if(e.message.match('subscriptionDuplicate')) {
jQuery('#success').show();
} else {
jQuery('#fail').show();
alert("Please send us a mail () with the following: ERROR: " + e.message);
}
}
So, the first error comes with
YouTube.Subscriptions.insert(resource, 'snippet')
It says YouTube is not defined. I replaced it with:
gapi.client.youtube.subscriptions.insert(resource, 'snippet');
And that error went away. When checking response, as the subscription isn't completed, this is what I get
{"wc":1,"hg":{"Ph":null,"hg":{"path":"/youtube/v3/subscriptions","method":"POST","params":{},"headers":{},"body":"snippet","root":"https://www.googleapis.com"},"wc":"auto"}}
So, I would like to know what's happening on that POST request and what's the solution to this.
I can post the full OAuth file, but it's just as in the example, plus that addSubscription method at the end.
Okay, I got it working, the problem was on the POST request. Here is the full method working:
// Subscribes the authorized user to the channel specified
function addSubscription(channelSub) {
var resource = {
part: 'id,snippet',
snippet: {
resourceId: {
kind: 'youtube#channel',
channelId: channelSub
}
}
};
var request = gapi.client.youtube.subscriptions.insert(resource);
request.execute(function (response) {
var result = response.result;
if (result) {
// alert("Subscription completed");
}
} else {
// alert("Subscripion failed");
// ...
}
});
}
Also make sure to load Google Apps API (in fact without it the authorize/login button won't work) and jQuery.
Any chance you can post everything that made this work...all the JS entire auth.js save for your private keys, im working on this exact problem.

Why websocket sendMessage is required

This is the code taken from the book "The Definitive Guide to HTML5 websocket"
div id="output"></div>
<script>
function setup() {
output = document.getElementById("output");
ws = new WebSocket("ws://localhost:7777");
ws.onopen = function(e) {
log("Connected");
sendMessage("Hello Websocket!");
}
ws.onclose = function(e){
log("Disconnected: " + e.reason);
}
ws.onerror = function(e){
log("Error ");
}
ws.onmessage = function(e) {
log("Message received: " + e.data);
ws.close();
}
}
function sendMessage(msg){
ws.send(msg);
log("Message Sent");
}
function log(s){
var p = document.createElement("p");
p.style.wordWrap = "break-word";
Could anybody please let me know for what reason this below event is required ??.
ws.send(msg);
I understand that the below will call the onMessage method on server side as shown below
public void onMessage(String data) {
}
But the actual purpose of onMessage on server side is to send data from backend to the javascript which will inturn call onmessage of client side javascript .
could anybody please help me understand this .
In the above code the ws.onopen, ws.onclose, ws.onmessage are all events associated with WebSocket object.
Whereas ws.send() is a method associated with WebSocket object. There is a huge difference between them.
The following event ensures that the Web Socket is connected to the server i.e you've opened your connection
ws.onopen = function(e) {
//Once you've opened your connection
//you can begin transmitting data to the server
//using the following method
ws.send("You\'re message");
}
So the main purpose of ws.send() method is to transmit data from the client to the server which is done by simply calling the WebSocket object's send() [in your case ws.send(msg)].
And also send data only takes place once a connection is established with the server by defining an onopen event handler.

socketio client: How to handle socketio server down

I've got a socketio server/client working well together, however I want to start writing events for when the server is offline on page load or during normal run.
I'm including the remote socket.io code in my header:
<script src="<?=NODE_HOST?>/socket.io/socket.io.js"></script>
<script>
var nodeHost = '<?=NODE_HOST?>';
</script>
And in my client controller I have
if(typeof io != 'undefined')
this.socket = io.connect(this.settings.server);
else
this.handleDisconnect();
The function I have to attempt to re-connect over and over if a) A socket disconnect occurs during normal operation, or b) the server is down on page load
botController.prototype.handleDisconnect = function() {
$.getScript(nodeHost+"/socket.io/socket.io.js").done(function(script, textStatus) {
bot.control.socket = io.connect(bot.control.settings.server);
}).fail(function(jqxhr, settings, exception) {
setTimeout(function() {
bot.control.handleDisconnect();
}, 5000);
});
}
Am I going about this the correct way?
The main issue I have right now (which made me create this question) is my code errors on page load when the server is down because I have functions like:
socket.on(...
When socket doesn't yet exist. I could wrap those in a function and call it when I detect the global socket object exists on successful reconnection? Would it matter if that function that contains socket.on... is called multiple times (if the server goes down more than once during operation)?
OK I managed to come up with this solution that seems to work well using yepnope which I already had using Modernizr (it handles the cross domain issue for me too).
<script src="<?=NODE_HOST?>/socket.io/socket.io.js"></script>
<script>
var nodeHost = '<?=NODE_HOST?>';
</script>
// Attempt to connect to nodejs server
botController.prototype.start = function() {
// Is our nodejs server up yet?
if(typeof io != 'undefined') {
this.socket = io.connect(this.settings.server);
this.startSocketEvents();
} else {
this.handleDisconnect();
}
}
// Our connection to the server has been lost, we need to keep
// trying to get it back until we have it!
botController.prototype.handleDisconnect = function(destroySocketObject) {
if(destroySocketObject === undefined)
destroySocketObject = true;
// Destroy any cached io object before requesting the script again
if(destroySocketObject)
io = undefined;
yepnope.injectJs(nodeHost+"/socket.io/socket.io.js",
function(result) {
// Did it actually download the script OK?
if(typeof io != 'undefined') {
bot.control.socket = io.connect(bot.control.settings.server);
bot.control.startSocketEvents();
} else {
setTimeout(function() {
bot.control.handleDisconnect(false);
}, 5000);
}
}
);
Where startSocketEvents() function contains all of my socket.on events

Socket.io as server, 'standard' javascript as client?

So i've built a simple websocket client implementation using Haxe NME (HTML5 target ofc).
It connects to
ws://echo.websocket.org (sorry no link, SO sees this as an invalid domain)
which works perfectly!
(i'm using xirsys_stdjs haxelib to use the HTML5 websocket stuff.)
I want to have a local (on my own machine) running websocket server.
I'm using Socket.io at the moment, because i cannot find an easier / simpler solution to go with.
I'm currently trying to use socket.io as socket server, but a 'standard' javascript socket implementation as client (Haxe HTML5), without using the socket.io library clientside.
Does anyone know if this should be possible? because i cannot get it working.
Here's my socket.io code:
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(1337);
function handler (req, res) {
fs.readFile(__dirname + '/client.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
// WEBSOCKET IMPLEMENTATION
io.sockets.on('connection', function (socket) {
console.log("webSocket connected...");
socket.on('message', function () {
console.log("server recieved something");
// TODO: find out how to access data recieved.
// probably 'msg' parameter, omitted in example?
});
socket.on('disconnect', function () {
console.log("webSocket disconnected.");
});
});
And here's my Haxe (client) code:
static var webSocketEndPoint:String = "ws://echo.websocket.org";
//static var webSocketEndPoint:String = "ws://localhost:1337";
...
private function initializeWebSocket ():Void {
if (untyped __js__('"MozWebSocket" in window') ) {
websocket = new MozWebSocket(webSocketEndPoint);
trace("websocket endpoint: " + webSocketEndPoint);
} else {
websocket = new WebSocket(webSocketEndPoint);
}
// add websocket JS events
websocket.onopen = function (event:Dynamic):Void {
jeash.Lib.trace("websocket opened...");
websocket.send("hello HaXe WebSocket!");
}
websocket.onerror = function (event:Dynamic):Void {
jeash.Lib.trace("websocket erred... " + event.data);
}
websocket.onmessage = function (event:Dynamic):Void {
jeash.Lib.trace("recieved message: " + event.data);
switchDataRecieved(event.data);
}
websocket.onclose = function (event:Dynamic):Void {
jeash.Lib.trace("websocket closed.");
}
}
In case the Haxe code is unclear: it's using 2 extern classes for the webSocket implementation: MozWebSocket and WebSocket. These are just typed 'interfaces' for the corresponding JavaScript classes.
websocket.io! from the same guys. sample shows exact same thing that you are asking about... and something that I spent past 20 hours searching for (and finally found!)
https://github.com/LearnBoost/websocket.io
Update: Jan 2014
The websocket.io repository has not seen any activity for about 2 years. It could be because it is stable, or it could be because it is abandoned.
The same people have another repository called engine.io. In the readme they say that this is isomorphic with websocket.io... It seems that engine.io is where all the action is these days.
https://github.com/LearnBoost/engine.io
While searching for the same thing I just found https://github.com/einaros/ws/ and its server example worked for me with my pre-existing plain javascript client.
http://socket.io/#how-to-use
At the mentioned link, down towards the bottom of the page,
the socket.io documentation demonstrates as it's last
example, how to use their module as a plain
old xbrowser webSocket server.
SERVER
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket)
{
socket.on('message', function () { });
socket.on('disconnect', function () { });
});
BROWSER
<script>
var socket= io.connect('http://localhost/');
socket.on('connect', function ()
{
socket.send('hi');
socket.on('message', function (msg)
{ // my msg
});
});
</script>
Hope that's what your looking for
--Doc

Resources