how to get socket.id of a connection on client side? - javascript

Im using the following code in index.js
io.on('connection', function(socket){
console.log('a user connected');
console.log(socket.id);
});
the above code lets me print the socket.id in console.
But when i try to print the socket.id on client side using the following code
<script>
var socket = io();
var id = socket.io.engine.id;
document.write(id);
</script>
it gives 'null' as output in the browser.

You should wait for the event connect before accessing the id field:
With this parameter, you will access the sessionID
socket.id
Edit with:
Client-side:
var socketConnection = io.connect();
socketConnection.on('connect', function() {
const sessionID = socketConnection.socket.sessionid; //
...
});
Server-side:
io.sockets.on('connect', function(socket) {
const sessionID = socket.id;
...
});

For Socket 2.0.4 users
Client Side
let socket = io.connect('http://localhost:<portNumber>');
console.log(socket.id); // undefined
socket.on('connect', () => {
console.log(socket.id); // an alphanumeric id...
});
Server Side
const io = require('socket.io')().listen(portNumber);
io.on('connection', function(socket){
console.log(socket.id); // same respective alphanumeric id...
}

The following code gives socket.id on client side.
<script>
var socket = io();
socket.on('connect', function(){
var id = socket.io.engine.id;
alert(id);
})
</script>

To get client side socket id for Latest socket.io 2.0 use the code below
let socket = io();
//on connect Event
socket.on('connect', () => {
//get the id from socket
console.log(socket.id);
});

Related

Sending Data to Target Client with socket.io

For example, in the client side, i have two registred and online user.
UID 1 : Leon
UID 2 : Albert
Leon wants to know how much have credit.
for example, Leon hit the button to get credit, so:
socket.emit('my_credit', 1);
And in the server side, i use this code:
Example:
var express = require('express');
var server = express();
var app = require('http').createServer(server);
var io = module.exports.io = require('socket.io')(app);
io.on('connection', function(socket){
socket.on('my_credit', function(uid){
getUserCredit(uid, (result) => {
socket.emit('my_credit', result);
})
});
});
Now, in the client side, all users receive this value!
If I want only Leon to receive this value, how can i do ?
How can i do in the server side to find currect id ?
For sending message to target client, use to function:
Eg:
io.sockets.to(/* Unique ID */).emit('message');
Or:
io.on('connection', function (socket) {
socket.on('check', function(){
io.sockets.to(socket.id).emit('check', 'Just You: ' + socket.id);
});
});
Yo!
So basically, at the moment, I dont know any other solutions than checking socket id.
Example to emit client side:
socket.emit('my_credit', {user: 1, id: socket.id});
Receiving server side :
var express = require('express');
var server = express();
var app = require('http').createServer(server);
var io = module.exports.io = require('socket.io')(app);
io.on('connection', function(socket){
socket.on('my_credit', function(uid){
getUserCredit(uid.user, function(result){
socket.emit('my_credit', {res: result, id: uid.id});
})
});
});
And receiving client side :
socket.on('my_credit', (message) => {
if (message.id !== socket.id) return;
// your code here
})

Connect to a third party socket.io server

I'm creating a socket.io server like so:
var http = require('http');
var io = require('socket.io');
var port = 8080;
var server = http.createServer(function(req, res){
res.writeHead(200,{ 'Content-Type': 'text/html' });
res.end('<h1>Hello Socket Lover!</h1>');
});
server.listen(port);
// Create a Socket.IO instance, passing it our server
var socket = io.listen(server);
// Add a connect listener
socket.on('connection', function(client){
console.log('Connection to client established');
// Success! Now listen to messages to be received
client.on('message',function(event){
console.log('Received message from client!',event);
});
client.on('disconnect',function(){
clearInterval(interval);
console.log('Server has disconnected');
});
});
console.log('Server running at http://127.0.0.1:' + port + '/');
The server works fine and starts, however when I'm connecting through js like this:
$(function(){
var socket = io();
socket.connect('http://localhost:8080');
});
It's not connecting and I'm getting this in dev tools console.
polling-xhr.js:264 GET http://file/socket.io/?EIO=3&transport=polling&t=Lz53lhL net::ERR_NAME_NOT_RESOLVED
I'm loading socket.io.js like this:
<script src="http://127.0.0.1:8080/socket.io/socket.io.js"></script>
Change
$(function(){
var socket = io();
socket.connect('http://localhost:8080');
});
to
$(function(){
var socket = io('http://localhost:8080');
});
You need to pass the url of your socket server to the io function

io.on is not a function

I have this code working for receiving data from my Arduino but I will like to send data back to my Arduino and get a response on my client page. I added a listening function but I keep getting io.on is not a function when I send data from my client page.
test.js
io.listen(app.listen(3000)).on('connection', function (client) {
// store client into array
clients.push(client);
// on disconnect
client.on('disconnect', function() {
// remove client from array
clients.splice(clients.indexOf(client), 1);
});
// I added this to listen for event from my chart.JS
io.on('connection', function(socket){
socket.on('LED on', function (data) {
console.log(data);
});
socket.on('LED off', function (data) {
console.log(data);
});
});
});
Your value of io is not what it should be.
The usual way of doing things is like this:
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');
app.listen(80);
io.on('connect', ...);
But I'm guessing that your value of io is something like this:
var io = require('socket.io');
That's not the same thing. That's the module handle. But, when you do it this way:
var io = require('socket.io')(app);
Then, io is a socket.io instance. You can bind listeners to an instance, not to the module handle.
In every single socket.io server-side example on this doc page, they use one of these forms:
var io = require('socket.io')(app);
var io = require('socket.io')(port);
var io = require('socket.io')(server);
with this:
io.on('connection', ....);
Nowhere do they do:
var io = require('socket.io`);
io.listen(server);
io.on('connection', ....);
That's just the wrong value for io.
Long story, shortened, you need to fix what you assign to io to be consistent with the docs. It's the return value from require('socket.io')(app); that gives you a socket.io instance object that you can then set up event handlers on.
if you are using express
var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
let APP_PORT=3000;
server.listen(APP_PORT,()=>{
console.log(`SERVER RUNNING ON PORT : ${APP_PORT}`);
});
io.on('connection', (socket) => {
/* SOCKET - CORE EVENTS */
socket.on('connect', (message) => {
console.log("connected: " + message+"socket_id:"+socket.id);
});
socket.on('disconnect',(data)=>{
console.log('user disconnected:' + socket.id);
});
socket.on('error', function (err){
console.log('received error from client:', socket.id,' Error :',err);
});
});

User receive more than 1 notification from nodejs

This is my first time with nodejs and I have some issues with it. The main problem is that the user receive more than 1 signal from the server. The count is based on the refresh of the page.
Below is my code:
var http = require('http');
var server = http.createServer().listen(1332);
var io = require('socket.io').listen(server);
var redis = require('redis');
var sub = redis.createClient();
//Subscribe to the Redis chat channel
sub.subscribe('notification_count');
console.log("Server is running...\nClick on Ctrl+C to exit");
io.sockets.on('connection', function (socket) {
var user_id = socket["handshake"]["query"]["user_id"];
console.log("user_id", user_id);
socket.room = user_id;
socket.join(user_id);
socket.on('disconnect', function(){
socket.leave(socket.room);
});
//Grab message from Redis and send to client
sub.on('message', function(channel, message){
io.sockets.in(message).emit('message', message );
});
});
And here is the client side js code:
var socket = io.connect('localhost:1332', { query: "user_id={{ request.user.id }}" });
socket.on('connect', function(){
console.log("connected");
});
socket.on('message', function(message) {
//something
});
Basically on connection from the server I send to the server the user_id. After that I create a new room which name is the same as the user_id. Of course on disconnect the room should be delete. I have noticed that sub.on() is fired more than once, but I cannot figure out why. I will appreciate any help. Thank you in advance !
The problem is that you are using a handler inside the connection event, everytime a client connects it will execute everything inside the connection event including your sub.on
Place sub.on out of the connection event and it should stop the double messages

how to get session id of socket.io client in Client

I want to get session id of client in my socket.io client.
here is my socket.io client :
var socket = new io.Socket(config.host, {port: config.port, rememberTransport: false});
// when connected, clear out display
socket.on('connect',function() {
console.log('dummy user connected');
});
socket.on('disconnect',function() {
console.log('disconnected');
});
socket.connect();
return socket;
I want to get session id of this client , how can i get that ?
Have a look at my primer on exactly this topic.
UPDATE:
var sio = require('socket.io'),
app = require('express').createServer();
app.listen(8080);
sio = sio.listen(app);
sio.on('connection', function (client) {
console.log('client connected');
// send the clients id to the client itself.
client.send(client.id);
client.on('disconnect', function () {
console.log('client disconnected');
});
});
On socket.io >=1.0, after the connect event has triggered:
var socket = io('localhost');
var id = socket.io.engine.id
I just had the same problem/question and solved it like this (only client code):
var io = io.connect('localhost');
io.on('connect', function () {
console.log(this.socket.sessionid);
});
* Please Note: as of v0.9 the set and get API has been deprecated *
The following code should only be used for version socket.io < 0.9
See: http://socket.io/docs/migrating-from-0-9/
It can be done through the handshake/authorization mechanism.
var cookie = require('cookie');
io.set('authorization', function (data, accept) {
// check if there's a cookie header
if (data.headers.cookie) {
// if there is, parse the cookie
data.cookie = cookie.parse(data.headers.cookie);
// note that you will need to use the same key to grad the
// session id, as you specified in the Express setup.
data.sessionID = data.cookie['express.sid'];
} else {
// if there isn't, turn down the connection with a message
// and leave the function.
return accept('No cookie transmitted.', false);
}
// accept the incoming connection
accept(null, true);
});
All the attributes, that are assigned to the data object are now accessible through the handshake attribute of the socket.io connection object.
io.sockets.on('connection', function (socket) {
console.log('sessionID ' + socket.handshake.sessionID);
});
On Server side
io.on('connection', socket => {
console.log(socket.id)
})
On Client side
import io from 'socket.io-client';
socket = io.connect('http://localhost:5000');
socket.on('connect', () => {
console.log(socket.id, socket.io.engine.id, socket.json.id)
})
If socket.id, doesn't work, make sure you call it in on('connect') or after the connection.
For some reason
socket.on('connect', function() {
console.log(socket.io.engine.id);
});
did not work for me. However
socket.on('connect', function() {
console.log(io().id);
});
did work for me. Hopefully this is helpful for people who also had issues with getting the id. I use Socket IO >= 1.0, by the way.
Try from your code
socket.socket.sessionid
ie.
var socket = io.connect('http://localhost');
alert(socket.socket.sessionid);
var sendBtn= document.getElementById('btnSend');
sendBtn.onclick= function(){
var userId=document.getElementById('txt1').value;
var userMsg = document.getElementById('txt2').value;
socket.emit('sendto',{username: userId, message: userMsg});
};
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
socket.on('message',function(data){ console.log(data);});
Try this way.
var socket = io.connect('http://...');
console.log(socket.Socket.sessionid);

Categories