JS Socket | Add full array on the site - javascript

So I have a kinda bug on my socket system. I have a array which will be emited if new connection is made to the site, but the problem is that it will be called on all users. So if I have there console.log('new user') then everyone will receive it to the console. My question is, how can I do it so the only one user who just connected receives only it?
Here is my server
io.on('connection', function(client){
clients.push(client.id);
io.emit('add games', coinflips); //This is the line
console.log(clients);
client.on('disconnect', function(){
clients.splice(client.indexOf, 1);
console.log(clients);
});
});
Here is how it's being handled
socket.on('add games', function(data){
if(data.length > 0){
addGames(data);
}
});

you can use the the socket id, socket.id then send to that id.
something along this line.
io.of('/mynamespace').sockets[socketID].emit(...)
Event this logic could work
clients = [];
then whenever a connection is made.
clients.push(socket);
then in the clients array, just index it.
clients[0].emit(...)
this is how you get a id upon connection.
console.info('Client id (id=' + socket.id + ').');
Socket.IO allows you to “namespace” your sockets, which essentially means assigning different endpoints or paths.
Namespaces are useful features to minimize the number of resources (TCP connections) and at the same time separate concerns within your application by introducing separation between communication channels. Multiple namespaces actually share the same WebSockets connection thus saving us socket ports on the server.
Namespaces are created on the server side. But they are joined by clients by sending a request to the server.
---------------------------------------------------------------
Default Namespaces
The root namespace '/' is the default namespace which is joined by clients if a namespace is not specified by the client while connecting to the server. All connections to the server using the socket object client side are made to the default namespace.
--------------------------------------------------------
Custom Namespaces
We can create our own custom namespaces. To set up a custom namespace, we can call the of function on the server-side:
---------------------------------------------------------
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendfile('index.html');
});
var nsp = io.of('/my-namespace');
nsp.on('connection', function(socket){
console.log('someone connected');
nsp.emit('hi', 'Hello everyone!');
});
http.listen(3000, function(){
console.log('listening on localhost:3000');
});

Related

How to change URL Websocket NodeJs (server/client)

I have a server node Js with express I want to use two socket with my clients in the same page server.js (contains all my controllers), suddenly I want to put the first socket under the url ("/connection"), and A second one under the url ("/giveUserConnected") that will serve me to recupir the connected users, par exemple :
client.html :
var socket = io.connect('http://127.0.0.1:9999/connection');
To contact server.js :
app.get('/connection',function (req,res) {
io.on('connection', function(socket){
console.log('a user connected');
});
});
and another socket2 in client.html :
var socket2 = io.connect('http://127.0.0.1:9999/giveUserConnected');
to contact server.js :
app.get('/giveUserConnected',function (req,res) {
io.on('connection', function(socket){
// to recuper list of users connected
});
});
but it does not work
what is the solution , thank's
You are mixing HTTP requests with socket.io requests, which are two different things.
When you provide a path name to io.connect() (in this case, /connection and /giveUserConnected), the socket.io server uses the path as the name to a namespace that the client connects to.
What I think you want is to just create an event handler for a particular message that will return the list of users. You could use acknowledgement functions for that:
// server
io.on('connection', function(socket) {
socket.on('giveUserConnected', function(fn) {
fn(listOfUsers);
});
});
// client
socket.emit('giveUserConnected', function(users) {
...
});
What listOfUsers is depends on your app.

socket.io - emit to socketid(single client) not working

I am using version 0.9.4 (I can use any version as per your guidance)
in server (app.js), I am storing socket id like this:
var socket_ids = [];
io.sockets.on('connection', function(socket) {
socket_ids.push(socket.id); #This is how I am getting socket id. My real code logic is totally different, but getting socket id using socket.id;
socket.on('createNote', function(data) {
socket.broadcast.to(socket_ids[0]).emit('onNoteCreated', data);
});
});
In short, I have 4 people opened sessions, all 4 are different users.
When p1 sends message, it should reach p2 only.
When p3 sends message, it should reach p4 only.
Keeping the if..else logics aside(I am fine with that), when I am broadcasting message using socket id, the client/browser with that socket id is not receiving that message. Also, above above broadcast line of code(other lines are custom for SO) not giving errors but client not receiving.
But these clients/browsers receiving messages when broadcasted to everything.
Thanks.
With the latest socket.io version, this is how I would do it:
var sockets = [];
io.on("connection", function(socket){
// Store whole socket object.
// NOTE: You should probably loop through sockets array
// to see if a socket with this id already exists
sockets.push(socket);
socket.on("createNote", function(data){
sockets[0].emit("onNoteCreated", data);
});
});
Hope this helps

How can I establish one connection between a user and the WebSocket?

I have websocket running on a node/Express server.
I need to send json string back and fourth between a websocket and a client.
However, if a user opens more than one browser's tab, I like for the websocket server to know that this is the same user that is already connected.
Here is the logic execution order
A user connects to the WebSocket.
The user sends json string to the WebSocket.
The WebSocket does things to the received message.
WebSocket finally sends the new message to all the tabs that a user have open.
The new message should be returned only to that user not others.
How can I establish one connection between a user and the WebSocket?
This is my server setup
var env = require('./config');
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var clients = [];
server.listen(env.socket.port, env.socket.host, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Websocket running at http://%s:%s', host, port);
});
app.get('/', function (req, res) {
res.send('Welcome!');
});
io.on('connection', function (socket) {
clients[] = socket;
socket.emit('chat', { hello: 'world' });
socket.on('chat', function(msg){
console.log('message: ' + msg);
sendAll(msg);
});
});
function sendAll (message) {
for (var i=0; i< clients.length; i++) {
clients[i].send("Message For All: " + message);
}
}
If you do not have authentication for the users, then you need some browser-specific piece of data to correlate users on your backend.
I don't know about cookies (haven't used them), but one way at the JavaScript level would be to store a locally generated random ID (of sufficient length so that you don't have to worry about collisions) in local storage in the browser, and transmit this as part of the initial message at the WebSocket level.

Socketio send message to specific client in namespace

server side:
io.of('/lobby').on('connection', function(client) {
setInterval(function(){
io.to(client.id).emit('message','test');
},2000);
});
client side:
var ioLobby = io.connect('127.0.0.1:9001/lobby');
ioLobby.on('message',function(data){
console.log(data);
});
I'm trying to send a message to a specific client in socket.io version 1.2.1. I've verified that the socket joins the default room on the server side, but its not being triggered on the client side. Any ideas?
The line io.to(client.id) will only work if that user has first joined a room with that same name. You need something like
io.on('connection', function(socket){
socket.join('some room');
});
and then you can call io.to
io.to('some room').emit('some event'):
I compromised and ended up using
socket.emit()
The only downside in comparison is requiring a ref to the socket you're emitting to.

Extra params with socket.io

How can I send extra parameters with the connection in socket.io? So when a client connects, they send additional information, and server-side it is received as
io.on('connection', function(client, param1, param2, param3) {
// app code
}
Here's a little trick which should work. First, you create your own Socket client that sends a message on first connection (containing all your additional info).
// Client side
io.MySocket = function(your_info, host, options){
io.Socket.apply(this, [host, options]);
this.on('connect', function(){
this.send({__special:your_info});
});
};
io.util.inherit(io.MySocket, io.Socket);
var my_info = {a:"ping"}
var socket = io.MySocket(my_info);
Then on the server side, you modify your socket to listen for the special message and fire off an event when it does.
// Server side
var io = require('socket.io').listen(app);
io.on('connection', function(client){
client.on('message', function(message){
if (message.__special) {
io.emit('myconnection', client, message.__special);
}
});
});
io.on('myconnection', function(client, my_info) {
// Do your thing here
client.on('message', ...); // etc etc
}
This is the technique I used to link my session handling into Socket.IO for a package I wrote.

Categories