What's the difference? .on "connect" vs .on "connection" - node.js

I'm having difficulty understanding the difference between:
io.on('connection', function (){ });
io.on('connect', function,(){ });
May be quite a primitive question, however I was unable to find clear documentation about it. Would love to learn the difference.

These are different names of the same thing.
As written in socket.io docs:
Event: connection is synonym of Event: connect. Which connect fired upon a connection from client.

I agree with mabe.berlin's idea about the order of these events.
Run:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function(socket){
console.log('connection',socket.id);
io.on('connect',function (socket) {
console.log('conenct',socket.id);
});
});
http.listen(1111);
And you will get something like:
connection 6Song1KpSUoUkKgPAAAA
But if you try
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connect',function (socket) {
console.log('conenct',socket.id);
io.on('connection', function(socket){
console.log('connection',socket.id);
});
});
http.listen(1111);
You are supposed to get something like:
conenct pSlSKNaabR2LBCujAAAA
connection pSlSKNaabR2LBCujAAAA
It proves that socket.io will process connect first then connection.

From naming:
io.on('connection', function (socket) { }); is called directly after the connection has been opened.
io.on('connect', function () { }); is called directly before the connection will be opened.
but on quick reading code (https://github.com/Automattic/socket.io/blob/master/lib/socket.js) it looks like the event name connect is emitted after the connection has been opened and there is no event named connection.

Related

I can't setup socket in my page with Socket.io

How can I setup socket in client at my page with url
/localhost:3000/post/:id
In client I set
socket=io("http://localhost"3000/post/:id")
but when I listen in server with io.on("connection") , it isn't active.
In the client side you just need to include the socket.io cdn file and when you are on same host you don't have to include the full url.
code sample for client side :
let socket = io.connect();
socket.emit("connection",{});
For better understanding please view documentation as said on previous comment.
This is how you should configure it :
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
io.on('connection', (socket) => {
console.log('a user connected');
});
http.listen(3000, () => {
console.log('listening on *:3000');
});
Read this documentation to understand it better https://socket.io/docs/v3

I have a two node js servers. second server is for the socket connection. How do I establish a connection between these two servers?

I'm setting up another nodejs server for the socketio, which is index.js. so I have two servers one is app.js and other one is index.js. so how do i establish a connection between these two servers?
If I correctly get what you wanted to do. You wanted to separate the file of the recieving of socket. Here's my code below.
on your app.js
var app = Express();
var server = require('http').createServer(app);
var io = SocketIo.listen(server);
server.listen(function(){
require('/path/of/your/index.js')(io);
})
and on your index.js
module.exports = function(io){
io.on('connection', function(socket){
*your codes here*
});
}
Can you please explain your problem in detail.And second thing, I don't understand why you want to establish two servers.Because you can always connect socket.io using your Node server.The code for it is below:
//Server side code
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');
app.listen(80);
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
//Client Side code
var socket = io.connect();
socket.emit('my other event', {
data : 'Hello'
});
This is very basic example for client-server communication using socket.io
I hope you will get your answer.

Socket io on connection not connecting NodeJS

I just started learning NodeJS and I am trying to make a simple server-client project using Socket io.
What happens right now is that when I open localhost:8001, I don't see any logs inside the listener.sockets.on block.
var http = require('http');
var app = http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('<h1>Hello!</h1>');
}).listen(8001);
var io = require('socket.io');
var listener = io.listen(app);
console.log("Sample Socket IO");
listener.sockets.on('connection', function (socket) {
console.log('a user connected');
socket.emit('connected', 'Welcome');
socket.on('disconnect', function () {
console.log('user disconnected');
});
});
It looks like the logging will occur when a connection happens. You setup a listening socket, so try to connect to it. Try 'telnet 127.0.0.1 8001' to connect.
The browser page needs to load the socket.io client code for one thing. That is the first thing missing that I can see. Look through the example here http://socket.io/get-started/chat/ and make sure you are following exactly at first and then make changes after you get that example working. Your server code looks a bit different from their example also.

Node js - Socket.io-client is not connecting to socket.io server

I am trying to connect to a socket.io-client using the following code:
Server:
// Load requirements
var http = require('http'),
io = require('socket.io');
// Create server & socket
var server = http.createServer(function(req, res){
// Send HTML headers and message
res.writeHead(404, {'Content-Type': 'text/html'});
res.end('<h1>Aw, snap! 404</h1>');
});
server.listen(8080);
io = io.listen(server);
// Add a connect listener
io.sockets.on('connection', function(socket) {
console.log('Client connected.');
// Disconnect listener
socket.on('disconnect', function() {
console.log('Client disconnected.');
});
});
Client:
console.log('1');
// Connect to server
var io = require('socket.io-client')
var socket = io.connect('localhost:8080', {reconnect: true});
console.log('2');
// Add a connect listener
socket.on('connect', function(socket) {
console.log('Connected!');
});
console.log('3');
I don't get the Connected console log or Client Connected console log and I don't know why! The code sample is taken from another question posted: Link and I don't see any solution to the problem...
Use the same version of socket io client and server. It will work perfectly.
Also you need to add protocol with path.
change
var socket = io.connect('localhost:8080', {reconnect: true});
to
var socket = io.connect('http://localhost:8080', {reconnect: true});
Assuming you are using a socket.io version greater than 1.0, on the server, change this:
// Add a connect listener
io.sockets.on('connection', function(socket) {
console.log('Client connected.');
// Disconnect listener
socket.on('disconnect', function() {
console.log('Client disconnected.');
});
});
to this:
// Add a connect listener
io.on('connection', function(socket) {
console.log('Client connected.');
// Disconnect listener
socket.on('disconnect', function() {
console.log('Client disconnected.');
});
});
See the socket.io documentation reference here.
You don't want to be listening for this event only on already connected sockets. You want to listen for this event on any socket, even a newly created one.
Also, be very careful when reading socket.io code in random places on the internet. Some things changed significantly from v0.9 to v1.0 (I don't know if this was one of those things or not). You should generally always start with the socket.io documentation site first since that will always represent the latest version. Then, if looking at other internet references, make sure you only use articles that are later than mid-2014. If you don't know the vintage of an article, it's best not to rely on it without corroboration from a more recent article.
you can use localhost. It works for me as well. You must use your ip address and port that works for you

How I can CLOSE socket.io server?

Here is my code:
var app = express();
var server = http.createServer(app);
var io = socketio.listen(server);
var sockets = [];
io.sockets.on('connection',function(socket){
console.log('client connecting');
sockets.push(socket);
});
server.listen(5000);
setTimeout(function(){
io.server.close(); // same as server.close()
sockets.forEach(function(socket){
socket.disconnect(true);
});
},5000);
After 5 sec timeout I still receive connections... How to stop it? I want to just KILL it forever!
According to the source code (see disconnect(close) method), it requires true parameter for closing underlying connection.
socket.disconnect(true);
You can use
socket.destroy();
You might be receiving connections because of reconnection attempts made by clients.

Resources