Is there any way to make Skipper work with socket.io? - socket.io

My problem is as simple as annoying. I'm developing a Sailsjs app, and I would just like to use socket.io to upload a file.
I usually make use of Skipper which is the recommended Sails' upload handler, but the req.file() object stay undefined (though it work well with http requests).

Skipper is not capable of that. At least I cannot find any proof in the documentation: https://github.com/balderdashy/skipper
Since sails#0.11.0 there is support for socket.io v1.2.1 which has support for binary data transfer:
http://socket.io/blog/introducing-socket-io-1-0/#binary-support
You want to transfer data from client to server. However most example you find is the other way round, e.g. https://stackoverflow.com/a/24124966/401025:
Server sends image to client:
require('socket.io')(3000).on('connection', function(socket){
require('fs').readFile('image.png', function(err, buf){
socket.emit('image', { image: true, buffer: buf });
});
});
Client receives image:
socket.on("image", function(image, buffer) {
if(image){
// do something with image
}
});
I have not tested if it works from client to server. You have to try ;)

Related

Force upgrade after fallback to polling?

This may be a stupid question, but i am wondering if there is a way to force socket.io to periodically retry to use websocket as transport instead of polling?
I noticed that sometimes my application cannot establish a websocket connection (Handshake failed: ERR_CONNECTION_RESET). Socket.io correctly falls back to polling then, but it never seems to try to switch back to websockets again, even if it would work. Is my observation correct?
If so, what would you suggest?
Please let me know if you need any code. I couldn't really think of a relevant code example, since this is more like a theoretical question.
Socket.io correctly falls back to polling then, but it never seems to try to switch back to websockets again, even if it would work. Is my observation correct?
Yes, correct.
If so, what would you suggest?
I dont think its a job of a lib to try to reastablish connection. You can set your own listener, that checks server availability - some times servers crash and users wont notice that they dont have connection anymore...
Kinda example of what we have on client side, hope it helps digging.
//If sockets close
window.ws.onclose = function (e) {
ws.onclose = null;
ws.onerror = null;
ws.onopen = null;
// restart sockets in: 3000 ms
setTimeout(function () { ctx.createWS(); }, 3000);
};
window.ws.onerror = function (error) {
//On error we will try to restart sockets in function described before
ws.close();
};

Should I use HTTP or xmlhttprequest on node.js? When?

I'm still exploring REST, node.js and generally web development. What I found out is that xmlhttprequest is mostly(if not always) used when using AJAX. As I learned AJAX is for asynchronous Javascript and XML. So my question is should I be using xmlhttprequest in my node.js project, just when I want to do asynchronous parts on my webpage? or does node.js HTTP also have opportunity to asynchronous javascript? How can I balance well the use of HTTP and xmlhttprequest(or AJAX) so that I don't get too messy in all my REST API stuff?
P.S. I kinda don't want to use AJAX, because of XML. I have heard that XML is much heavier in data than JSON and isn't worth using anymore. Is it true? What would you recommend me to do?
non async on node?
you're trying to build an endpoint api so all the other cases of not using async should be thrown out the window. As soon as you have a single non async code in your node.js project it will freeze the entire process until it is complete. Remember Node.js runs a single Thread (theoretically) which means all the other concurrent users are gonna get frozen.. that's one way to make people really upset.
say for instance you need to read a file from your Node.js server on a get request from a client (let's say a browser) well you want to make it a callback/promise never do non-async with an API server there is just no reason not to (in your case).
example below
import * as express from "express";
import * as fs from 'fs';
let app = express();
app.get('/getFileInfo', function(req, res) {
fs.readFile('filePath', 'UTF-8', function(err, data) {
if (err) {
console.log(err);
res.json({error: err});
} else {
res.json({data: data});
}
})
});
//users will freeze while the file is read until it is done reading
app.get('/nonasync', function(req, res) {
let data = fs.readFileSync('path', 'utf-8');
res.json({data:data});
});
the exact same idea applies to your web browser.. if you are going to not do something async in the browsers javascript the entire web application will be unresponsive because it also runs in the same manner, it has one main loop and unless they are in callbacks/promises/observable the website will freeze. Ajax is a much neater/nicer way to implement post/get/put/delete/get:id from a server then an XMLHttpRequest. now both of these have an option to send and receive JSON not only XML. Ajax is safer due to supporting different browser compatibility specs as XMLHttpRequest has some limitations in IE and Safari I believe.
NOTE: if you're not using a framework with node.js you should, it helps keep your endpoints neat and testable along with being able to pass the project on to others without them having to learn the way you implemented your req, res structure
some frameworks for node
Express 4 (my preference, api doc is really really good and strong
community)
Restify (used by Netflix - really light)
Hapi (never used but heard of)
some frameworks for web browsers you might like
angular 2 (my preference as I'm from a MEAN stack)
reactJS (created by big blue Facebook)
knockoutJS (simple and easy)
all the browser frameworks have their own implementation of the RESTful api's, but more are leaning towards Observable objects.

How to disconnect all sockets serve side using socket.io?

How can I disconnect/close all sockets on server side ?
Maybe restarting the socket.io module from the server side ?
(using the lateste socket.io)
Unfortunately, socket.io does not have a publicly documented interface that has been the same from one version to the next to do such a basic function as iterate all connected sockets. If you want to follow the entire history of various ways to do this, then you can follow the whole version history in this question: Socket.IO - how do I get a list of connected sockets/clients?, but you have to pay attention only to answers that apply to specific socket.io versions you are using and then test them for your specific version.
As of Aug 2018, attempting to use only documented interfaces in socket.io, one could use either of these to get a list of connected sockets and then just iterate over them to disconnect them as shown above:
function getConnectedSockets() {
return Object.values(io.of("/").connected);
}
getConnectedSockets().forEach(function(s) {
s.disconnect(true);
});
Depending upon the client configuration, the clients may try to reconnect.
You could also just maintain your own connect socket list:
const connectedSockets = new Set();
io.on('connection', s => {
connectedSockets.add(s);
s.on('disconnect', () => {
connectedSockets.delete(s);
});
});
function getConnectedSockets() {
return Array.from(connectedSockets);
}
getConnectedSockets().forEach(function(s) {
s.disconnect(true);
});
If you are using an older version of socket.io (particularly before v1.4), you will have to either test this to make sure it works in your older version or follow the version history in the above mentioned reference and find an answer there that targets your specific version of socket.io.
For me, jfriend00's solution didn't work (as of today).
I had to do this:
Object.keys(io.sockets.sockets).forEach(function(s) {
io.sockets.sockets[s].disconnect(true);
});

WebSockets + Haxe?

I need to develop an application using WebSockets and Haxe.
I came upon this lib: http://lib.haxe.org/p/hxWebSockets
But it's outdated.
Then I found this blog post: http://bp.io/post/322
But the links to the code are broken :(
So, anyone out there knows any other WebSocket resource for Haxe?
If not, does someone has a clue where to start looking to start implementing my own solution?
Thanks!
If you use node.js as a platform, I'd recommend you to make bindings to socket.io. If you use another platform, I'd recommend to use socket.io as a reference implementation, or just port it to haxe, which shouldn't be that hard.
The lib you mentioned is indeed outdated. Luckily, someone made a new one, supporting the latest websocket protocol:
http://lib.haxe.org/p/WebSocket
...however, it's still a bit lower level than nodejs/socket.io
I am using haxe for a websockets application and using the js libraries:
import js.html.WebSocket;
Using the following function to connect to the server.
private function connect() {
trace("Calling connect");
try {
websocket = new WebSocket(connectionString());
websocket.onclose = onClose;
websocket.onerror = onServerConnectionError;
var openStream = initializeElementStream(cast websocket, "open");
openStream.then(onOpen);
var eventStream = initializeElementStream(cast websocket, "message");
eventStream.then(onMessage);
var closeStream = initializeElementStream(cast websocket, "close");
closeStream.then(onClose);
var errorStream = initializeElementStream(cast websocket, "error");
errorStream.then(onServerConnectionError);
}catch(err : Dynamic) {
trace("Error establishing connection " + err);
}
trace("Connection successful");
}
Will this work for you. I am sticking to standard js libraries for my project. This has worked for me since the project has no external dependencies.
I recently started using Haxe-Js-Kit and it has decent bindings for a lot of nodejs libs including Socket.IO.
https://github.com/clemos/haxe-js-kit/
Make sure you use the dev branch for development as it is quite more advanced than the haxelib or master branch.

socket.io - Catch all event

I'm working on a Node.js application where pretty much all the communication is taking place via sockets.io.
What I need to do is, before processing any request (other than the login request) ensure that the user is authenticated.
The obvious way to do this would be to have a catch-all listener which is called prior to the execution of any method.
I can't seem to find anything like this in Socket.io, though. How can I achieve is? Is there a better approach than the one I'm taking?
The best approach here would be to authenticate the user upon connection (handshake), by parsing the cookie and decoding the session.
Read more about this in the following links:
http://www.danielbaulig.de/socket-ioexpress/ (this contains a detailed tutorial of everything you need to do)
https://github.com/LearnBoost/socket.io/wiki/Authorizing
socket.io and session?
Checkout out socket.io-events on nom for "Catching all events"
var router = requrie('socket.io-events')();
router.on('*', function (sock, args, cb) {
//do something with the args!
cb();
});
var io = require('socket.io')(3000);
Checkout out socket.io-handshake on nom for "socket.io v1.x session support"

Resources