Is there a callback for the io.connect() method in Socket.IO? - socket.io

Is there any callback for the io.connect() method on the client side? I would like to print some text about connection failure, otherwise proceed normally with the site's socket interactions.

Sure, checkout the documentation for Socket.IO-client with the examples there:
https://github.com/LearnBoost/socket.io-client#sockets-for-the-rest-of-us
socket.on('connect', function () {
// socket connected
});

In the current release of socket.io (1.3.x) you can use the connect_error event or the reconnect_failed event:
var socket = io(serverUrl);
socket.on('connect_error', function() {
console.log('Connection failed');
});
socket.on('reconnect_failed', function() {
console.log('Reconnection failed');
});
See: https://github.com/Automattic/socket.io-client#events

Related

Socket.emit() outside socket.on()

Do we always have to use socket.emit() inside a socket.on() like that:
io.sockets.on('connection', function (socket) {
console.log('User connected !');
retrieveDictionnary((dictionnary) =>{
socket.emit('dictionnarySend', dictionnary);
}
}
I want to create on my client side a function which ask information to the server when I click on a button:
translateServer(parameter, control){
this.socket.emit('translate', [parameter,control]);
}
But it seems that it's not working, the server never receive this message.
Thank you !
The pattern you are using above is the recommended way of interacting with a socket (ie acquiring a socket instance when the 'connection' event fires, and then calling emit() from that socket instance, etc).
If I understand your client-side requirements correctly, you are wanting to send data to the server via web sockets - are you sure the socket that you have established a web socket connection between the client and server?
For instance, if you add the following to your client-side code, you should see a success message in your console:
const socket = io.connect('YOUR SERVER ADDRESS');
socket.on('connect', () => {
console.log('connected to server!');
// [UPDATE]
// This assumes you have a <button> element on your page. When
// clicked, a message will be sent to the server via sockets
document.querySelector('button').addEventListener('click', (event) => {
// Prevent button click reloading page
event.preventDefault();
// Send message to server via socket
socket.emit('MESSAGE_ID', 'test message from client' + new Date());
});
});
Update
This shows your original server code, expanded with the detail needed to receive and print data sent from client via sockets:
io.sockets.on('connection', function (socket) {
console.log('User connected !');
// Register a server handler for any messages from client on MESSAGE_ID channel
socket.on('MESSAGE_ID', (message) => {
// Print the message received from client in console
console.log('message from client', message);
})
retrieveDictionnary((dictionnary) =>{
socket.emit('dictionnarySend', dictionnary);
}
}

socket.io connection event not firing in firefox

Im having something like the below code.
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io('http://localhost:8080');
socket.on('connect', function(){
socket.on('some-event', function(data) {});
});
socket.on('disconnect', function(){});
</script>
Inside the connect callback I have some code that responds to messages. This works perfectly fine on chrome. On first page load it works fine on firefox. If you reload the page then the connect event does not get called.
Im using 1.4.8 version of server and js client
I solved it using the following code. Not very clean but for the time being this helped us to progress with the project. As you can see the problem is the connect event not firing after a page reload, so I decided to attach the events after a timeout if connect was never fired.
function attachEventListners() {
socket.on('some-event', function(data) {});
}
var attached = false;
socket.on('connect', function(){
attachEventListners();
attached = true;
});
setTimeout(function() {
if (!attached) {
attachEventListners();
}
}, 1000);
You don't have to declare event listeners inside a connect listener, so even though I don't know a direct solution to your problem, I think this'll work around it:
<script>
var socket = io('http://localhost:8080');
socket.on('some-event', function(data) {});
socket.on('disconnect', function(){});
</script>
Because being able to receive messages implies that the socket is connected.
Instead of a timeout, you should use the load event listener on window
window.addEventListener("load",attachEventListners);

Socket.io client only joins room on every other connection

I've been trying to make a basic notification system that uses rooms in Socket.io. However, for some reason, it only works every other time you refresh the page.
I've simplified the code to make it easier to debug, but the issue remains. Each time I refresh the page, everything seems to work except joining a room (which only works half the time). What could be going on?
edit: I'm using Socket.io version 1.1.0 and Node.js version 0.10.31
edit2: Added FunnyLookinHat's suggestion (but it still doesn't solve the problem)
Client-Side Code:
socket = io.connect('example.com:8081'),
socket.on('connect', function () {
socket.on('startup', function(data) {
console.log(data.message);
});
socket.emit('joinRoom');
});
Server-Side Code:
var io = require('socket.io').listen(8081);
io.sockets.on('connection', function (socket) {
console.log(socket.id + ' connected!');
socket.emit('startup', { message: 'Socket started!' });
socket.on('joinRoom', function(){
console.log(socket.id + ' joining room lobby'); // prints on every other request
socket.join('lobby');
});
socket.on('disconnect', function() {
console.log(socket.id + ' disconnected!');
});
});
Client Console:
Socket started!
(refreshed page)
Socket started!
Server Console:
UIBqVuOiF1fegMIMAAAB connected!
UIBqVuOiF1fegMIMAAAB joining room lobby
UIBqVuOiF1fegMIMAAAB disconnected!
(refreshed page)
x3nMilBOjjFVjBFJAAAC connected!
(after about a minute once the client window has been closed or refreshed)
x3nMilBOjjFVjBFJAAAC disconnected!
Race condition! Try doing the following in your client code:
socket = io.connect('example.com:8081'),
socket.on('connect', function () {
socket.on('startup', function(data) {
console.log(data.message);
});
socket.emit('joinRoom');
});

"websocket was interrupted while page is loading" on Firefox for Socket.io

Error: The connection to <websocket> was interrupted while the page was loading.
Source File: localhost/socket.io/node_modules/socket.io-client/dist/socket.io.js
Line: 2371
I am new to socket.io and I have tried to search for this, but I didn't get an answer.
Websocket is interrupted when I refresh page on Firefox. That's why server side is waiting to authorise client.
Here is code:
server.js
var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
fs = require('fs')
app.listen(8080);
function handler(req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
socket.emit('news', {
hello: 'world'
});
socket.on('my other event', function (data) {
//alert(JSON.stringify(data));
console.log(data);
});
});
index.html
<script src="node_modules/socket.io-client/dist/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:8080');
socket.on('news', function (data) {
alert(JSON.stringify(data));
console.log(data);
socket.emit('my next event', { my: 'data' });
});
</script>
It happens because, you are not closing your open websocket.
This code would remove this error:
$(window).on('beforeunload', function(){
socket.close();
});
This seems to be an open bug in Firefox (as of 2015-03-29):
https://bugzilla.mozilla.org/show_bug.cgi?id=712329
The workaround (for now) is to call close() on the websocket on beforeunload, as Alexander pointed out.
Update 2016-04: According to Bugzilla, this will be fixed in Firefox 48
I was just running through the Socket.IO tutorials and I ran into this exact problem. I tried the posted solutions but they didn't seem to work at all.
After some fiddling and some screaming and some rubber-ducking, I finally figured out what the issue was. The issue is that it's trying to connect to the socket before the socket variables have been properly initialized. Javascript boo boo #1.
If you will ammend your file to include jQuery and then wrap your functions like so:
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(function(){
var socket = io.connect('http://localhost:8080');
socket.on('news', function (data) {
alert(JSON.stringify(data));
console.log(data);
socket.emit('my next event', { my: 'data' });
});
});
</script>
You will have much more success.
What impact does this have on your application? My guess is that it's just not great to see an error in the console.
The problem here is that you are seeing Firefox loggin this error and there's nothing you can do about it. It's not possible to capture this error with a try...catch block or via websocket.onerror/websocket.onclose.
See: How do I catch a WebSocket connection interruption?
Related:
Should WebSocket.onclose be triggered by user navigation or refresh?
Firefox - Race condition allows ghost WebSocket connections to live after tab closed
I've had this problem with our custom Undertow-based webserver for years -- my problem was that my server was not responding to the socket close message.
Based on a comment by Jan Wielemaker I checked my socket close handler code for AbstractReceiveListener.onFullCloseMessage and realized I had not called the super method. After adding super.close() the socket closes cleanly on the client and no error is emitted.
One solution is to put a timeout on the disconnect event.
setTimeout(() => {
$('#offlineModal').modal('show')
}, 5000)

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