How can I detect whether a socket.io server is connected? - node.js

I am developing an app using socket.io and appjs. I am having trouble giving a notice to the user when he causes EADDRINUSE by starting two instances of the app, which he is not supposed to.
Socket.io does detect EADDRINUSE, but I only receive a warning written to the console (not sure if stdout or stderr). I wanted an exception, a callback where I have an err parameter, or at the very least a flag to detect whether the connection is OK.
Just to clarify, I am trying to do this from the server side. In the client side I already have a timeout for client-server connections.
How can I do this?

EADDRINUSE is an error emitted by the net modules. Docs here: http://nodejs.org/api/net.html#net_server_listen_port_host_backlog_callback
In short you need to provide a callback to .on('error' that will handle the error.
server.on('error', function (e) {
if (e.code == 'EADDRINUSE') {
console.log('Address in use');
}
});

Related

Uncaught TypeError: socket.to is not a function

I want to emit some data to a room in socket.io.
According to the socket.io docs,
In one place (https://socket.io/docs/rooms-and-namespaces/#Joining-and-leaving) it is said,
io.to('some room').emit('some event');
And in another place (https://socket.io/docs/emit-cheatsheet/) it is said,
socket.to('some room').emit('some event', "description");
I tried both of these but got the error,
uncaught TypeError: io.to is not a function
and
uncaught TypeError: socket.to is not a function
All other socket.io functions i used worked except for this
I included
<script src="/socket.io/socket.io.js"></script>
in the head tag of the html file.
In the client side js file, i incuded
const socket = io.connect("http://localhost:3000/");
Also, I used socket.emit and it works the way it is supposed to.
Please tell me what is wrong with this..
If this Uncaught TypeError is happening on your client side, that's because io.to and socket.to are only server-side functions, and cannot be used on the client side. In the Client API part of the Socket.IO docs, it doesn't specify io.to and socket.to as valid API functions. Here is the client API docs.
And here is a snippet that you can use to emit to Socket.IO rooms:
Server
//Your code...
io.on("connection", socket => {
//Don't forget to do this!
socket.join("some room");
socket.on("some event", data => {
//Do socket.to if you want to emit to all clients
//except sender
socket.to("some room").emit("some event", data);
//Do io.to if you want to emit to all clients
//including sender
io.to("some room").emit("some event", data);
});
});
Client
//Remember to include socket.io.js file!
const socket = io.connect("http://localhost:3000");
socket.on("some event", data => { /* Whatever you want to do */ });
//To emit "some event"
//This will also emit to all clients in the room because of the way the server
//is set up
socket.emit("some event", "description");
If you need an explanation...
So what this does is, basically, since you can't emit to rooms on the client side (you can only emit to server), the client emits to the server, and the server emits the event to the room you want to emit to.
Hope this solves your problem :)
Step1: In the client-side js file, changes instead of io.connect("http://localhost:3000/") use given below line,
let io = require('socket.io').listen(server.listener);
Step2: You need to create a connection in (Both Client & serverSide) For the Testing purpose you can use check connection Establish or not Both End use can use Socket.io tester Chrome Extension.(https://chrome.google.com/webstore/detail/socketio-tester/cgmimdpepcncnjgclhnhghdooepibakm?hl=en)
step3: when a socket connection is Established in Both ends then you emit and listen to data Easily.
One thing when you listen to the data then sends Acknowledgement using Callback Function. I have Received data Successfully.
E.g.`
socket.on('sendMessage',async (chatdata,ack)=>{
ack(chatdata);
socket.to(receiverSocketId).emit('receiveMessage',chatdata);
});
`
yours, emitting a message is correct no need to change this one. But make sure and please check it again your socket connection is Establish successfully or not. another Shortcut way you can debug a code line by line you can easily resolve this problem.
I Hope using this approach you can resolve the Error, and it is help For a Future.
thanks:)

Handle Socket.io EADDRINUSE error in Node, it's "OK" to have the error

I'm building and application that uses many sockets, in some cases, two socket.io servers try to start with the same tcp port (this is expected actually), so one of them crashes with Error: EADDRINUSE.
What I want is to "catch" the error and then do something about it. I mean, the error in some cases is expected, but I want to handle it properly. I can't find a way to do it.
Thanks!
Thanks to #migg for his answer. The link provided contained two solutions, this one worked for me:
process.on('uncaughtException', function(err) {
if(err.errno === 'EADDRINUSE')
console.log(...);
else
console.log(err);
process.exit(1);
});

How to detect the socket server authorization failure on client side in socket.io?

I want to connect an js socket client to socket.io server using
socket = io.connect(). But on server side i m using io.use() method to check whether this socket connection contains cookies or not. I restrict the request on socket server to make connection if socket initial handshake does not contain cookies. by passing
next(new Error("Authentication Error")). But i m not able to catch this error on client side. I want to notify the client of invalid login session and login again.
Thanks
Thanks Andrey... I got success with
socket.on("error", function()
{
//function to perform on occurance of authorisation failure
})
I think you need to listen on connect_error:
socket.on('connection_error', function(data) {
// data here should be an Error object sent by server
});
The documentation is awful, but here is a little hint (found here):
Errors passed to middleware callbacks are sent as special error
packets to clients.

Error connecting mariadb - node.js?

I am using MariaDB in my node.js application. I am having the following code
var nodeMaria = require('node-mariadb');
var connection = nodeMaria.createConnection({
driverType: nodeMaria.DRIVER_TYPE_HANDLER_SOCKET,
host:'localhost',
port:9998
});
connection.on('error', function(err){
console.log(err);
process.exit(1);
});
connection.on('connect', function(){
console.log("mariadb connected");
});
Problem
After connecting the db, It is logging "mariadb connected".
After that Application is breaking without throwing any error.
Note: I had handled the error in connection connection.on('erorr',function(){});
Any help will be great.
If the application is closing, it doesn't necessarily mean that an error has occurred with connecting to MariaDB.
In fact, if there isn't anything keeping a node application explicitly open, it just closes after execution of the code.
What keeps a node application open? Event listeners. If you have an event listener listening for events, the node application doesn't close after finishing code execution. For example, if you have a http.listen command, which starts the web server and starts listening for incoming HTTP connections.

Node.js: What HTTP exceptions can it throw?

I have very simple server
http.createServer(function(request, response) {
response.writeHead(200);
response.end("Hello world");
}).listen(8080);
What exceptions can it throw except listen EADDRINUSE?
Can it thow an error if user disconnects in the middle of request sending? Or something like this?
It will not throw exception in such scenario as disconnected client - is very 'normal' behaviour.
The EADDRINUSE exception is thrown at the moment of calling http.createServer, as it tries to create socket and will fail in case if port is already in use.
While events you are talking, is behind the scenes stuff, like client disconnects, or timeouts, or similar. Those events is happening asynchronously and that is why they can't be just thrown to node.js execution in middle of nowhere.
You still have events for request it self, and have to subscribe to them, here are good answer that covers what you need: node.js http server, detect when clients disconnect

Resources