I am trying to update the number of users connected to the chat everytime a user connects, but is not working. It works for disconnect but not for connection.Here is the server
var socket = require( 'socket.io' );
var express = require( 'express' );
var http = require( 'http' );
var app = express();
var server = http.createServer( app );
var io = socket.listen( server );
server.listen( 8080 );
connections = [];
io.sockets.on( 'connection', function( client ) {
connections.push(client);
console.log( "---CONNECT--- INFO --> New user connected! >>>>> USERS ONLINE: %s", connections.length);
client.on('connection', function(data){
io.sockets.emit('connect', {users:connections.length});
});
client.on('disconnect', function(data){
connections.splice(connections.indexOf(client),1);
console.log("---DISCONNECT--- INFO --> User disconnected >>>>> USERS LEFT: %s", connections.length);
io.sockets.emit('disconnect', {users:connections.length});
});
client.on( 'message', function( data ) {
console.log( 'Message received from: ' + data.id);
io.sockets.emit( 'message', {id:data.id, name: data.name, avatar: data.avatar, message: data.message } );
});
});
If I do like this the disconnect stops working and the server stops working properly. If I emit outside the client.on which would be inside the io.sockets.on('connection') the server will crash.On the clients I have this:
var socket = io.connect( 'http://localhost:8080' );
socket.emit('connection');
socket.on('connect', function(data){
$("#usersOnline").html(data.users);
});
socket.on('disconnect', function(data){
$("#usersOnline").html(data.users);
});
You can use socket.join and socket.leave.
io.sockets.on( 'connection', function( client ) {
connections.push(client);
client.join('room', function(data){
//
});
client.leave('room', function(data){
//
});
});
Well since none of my other answers worked for some weird reason,
try emitting an event from the client on connection.
So on the client:
var socket = io.connect( 'http://localhost:8080' );
socket.emit("connection");
socket.on('connect', function(data){
$("#usersOnline").html(data.users);
});
socket.on('disconnect', function(data){
$("#usersOnline").html(data.users);
});
That should work since you already have the event listener on the server side for the client.on("connection") event.
Related
I have created one socket server in node js where I can send some data and receive from the server, but the problem is every time connection is closing and creating new PID for another request. here my requirement is once my IOT device connects to the server then the connection should stay there and I want to send, receive data any time.
Can anyone help me out?
I am posting my code below
Server code
var net = require('net');
// Create Server instance
var server = net.createServer(main);
server.listen(9010, function() {
console.log('server listening on %j', server.address());
});
function main(sock) {
sock.setEncoding("utf8");
sock.on('data', function(data) {
var data = data;
console.log('Request data is ', data);
console.log('Says:', data);
sock.write("responding to client");
sock.write(' exit');
});
sock.on('close', function () {
console.log('connection closed');
});
sock.on('error', function (err) {
console.log('Connection error: %s', err.message);
});
};
Client code
var net = require('net');
//params
var HOST = 'myhost';
var PORT = 9010;
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
client.write('Hello socket server');
});
client.on('data', function(data) {
console.log('Recieved data: ' + data);
client.destroy();
});
// Add a 'close' event handler for the client socket
client.on('close', function() {
console.log('Connection closed');
});
What is the best method to use a mysql fetched data during socket emiting time?
For example, I will have a data retrieved from database and now I would like to use that data on socket.emit('emit_name', function(data){ }).What will be the best way?
I firstly, tested with easy way to find if it works or not rather then diving beginning into complicated one from json.I used two data as 'type' and 'fruit' something like this on "Client side"
var socket = io.connect( 'http://localhost:8080' );
var nameVal = "Type";
var msg = "apple";
socket.emit( 'messages', { type : nameVal, fruit: msg } );
on Server side
var socket = require( 'socket.io' );
var express = require( 'express' );
var http = require( 'http' );
var app = express();
var mysql = require('mysql');
var server = http.createServer( app );
var io = socket.listen( server );
var pool = mysql.createPool({
connectionLimit : 10,
host: "localhost",
user: "root",
password: "",
database: "mydb"
}
);
io.sockets.on( 'connection', function() {
console.log( "User connected..!" );
io.client.on( 'messages', function(data) {
console.log( 'Message received ' + data.type + ":" + data.fruit );
});
});
server.listen(8080);
After doing this all I just started my node server and I get "connected" on my socket on page load but my work on socket side isn't working at all as I wised.The result(problem) on socket part of server side gives this error as below image :-
What might be the problem?How can I solve this issue?
This code is just wrong:
io.sockets.on( 'connection', function() {
console.log( "User connected..!" );
io.client.on( 'messages', function(data) {
console.log( 'Message received ' + data.type + ":" + data.fruit );
});
});
It should be this:
io.on( 'connection', function(socket) {
console.log( "User connected..!" );
socket.on( 'messages', function(data) {
console.log( 'Message received ' + data.type + ":" + data.fruit );
});
});
You have to use the socket variable that is passed to the io.on('connection, ...)` event to set event handlers on the newly connected socket.
In addition, this line of your client code:
socket.emit( 'messages', { type : nameVal, fruit: msg } );
may be running too soon before the socket has finished connecting. io.connect() is asynchronous. It does not complete immediately. If you try to send data before it is connected, then there is not yet a live socket to actually send the data on. It's possible that socket.io will cache that data until the socket connects (you'd have to check the socket.io code to see for sure), but it is much safer to wait for the connect event on the socket before sending data.
I am using a TCP connection via node.js to connect to a certain port in windows, however I want the connection to be established until the user logs out .
In other words I want to add the TCP Connection as a session attribute in node.js ,so that it will last as long as the session is alive for the user.
I have tried this ,but it doesn't work.
Code :
var express = require('express');
var authRouter = express.Router();
var createTCPConnection = function () {
var net = require('net');
var HOST = '127.0.0.1';
var PORT = 6969;
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
// Write a message to the socket as soon as the client is connected, the server will receive it as message from the client
client.write('I am Chuck1 Norris!');
});
// Add a 'data' event handler for the client socket
// data is what the server sent to this socket
client.on('data', function(data) {
// Close the client socket completely
//client.destroy();
});
// Add a 'close' event handler for the client socket
client.on('close', function() {
console.log('Connection closed');
});
return client;
};
authRouter.route('/').get(function(req, res) {
var sess = req.session;
if (sess.username) {
//If Session has username attribute, it is a valid session
res.render('dashboard', {
title : 'Welcome To Operator Screen',
username : sess.username
});
if(sess.tcpClient === undefined) {
console.log('Establishing TcpClient');
sess.tcpClient = createTCPConnection();
} else {
console.log('TcpClient already established');
}
} else {
//Invalid/expired session, redirect to homepage
res.redirect('/logout');
}
});
module.exports = authRouter;
i have code for server
server.js
var socket = require( 'socket.io' );
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = socket.listen( server );
var port = process.env.PORT || 3000;
var nik = {};
server.listen(port, function () {
console.log('Server listening at port %d', port);
});
io.on('connection', function (socket) {
socket.on( 'new_count_message', function( data ) {
io.sockets.emit( 'new_count_message', {
new_count_message: data.new_count_message
});
});
socket.on( 'update_count_message', function( data ) {
io.sockets.emit( 'update_count_message', {
update_count_message: data.update_count_message
});
});
});
and this is how i use that
$.ajax({
type: "POST",
url: "(some_url)",
data: $("id_form").serialize(),
dataType: "json",
beforeSend:function(){
alert('bla..bla..');
},
success: function (result) {
if (result.status) {
var socket = io.connect('http://' + window.location.hostname + ':3000');
socket.emit('new_count_message', {
new_count_message: result.new_count_message
});
} else if (result.status == false) {
alert(error);
return false;
}
},
error: function(xhr, Status, error) {
alert(error);
}
});
that function is working perfectly, but it send to all. how to send notif to specific user? i have the ID user that i want to send the notif
Thanks
Well,
With io.sockets.emit you emit a message to all sockets. Instead use io.sockets.in("roomname").emit("message").
As well if you have the socket ID where you want to send the message you can use io.sockets.connected["socketid"].emit("message").
If you are inside the io.on('connection') function and you want to send a message to the same socket you can simply use socket.emit.
Another way is:
When a new socket connects, add this socket to a specific room socket.join("UniqueUserId") or socket.join("UniqueUserSessionId") ... Then use the 1st option io.sockets.in("UniqueUserId").emit("message") or io.sockets.in("UniqueUserSessionId").emit("message")
Examples:
io.on('connection', function (socket) {
//get the unique socket socketId on connection
var socketId = socket.id;
//you can add this socket id to a Database to use it later, etc...
//use sessionStore like Redis or memStore to get a unique sessionId
//as well you can extract a cookie with the UserId (you need to secure this to be sure that the user not modified the cookie) (you can use 2 cookies 1 for the userid other for the encrypted password and check if the cookies data is the same than in your users Database) etc etc etc. User Session is a lot better). Read about nodejs session store and socket session. Something like...
var cookies = qs.parse(socket.handshake.headers.cookie, "; ");
var user_id = cookies.user_id; //or some other cookie name;
socket.join(user_id);
socket.on( 'new_count_message', function( data ) {
//all sockets
io.sockets.emit( 'new_count_message', {
new_count_message: data.new_count_message
});
//same Socket
socket.emit( 'new_count_message', {
new_count_message: data.new_count_message
});
//specific Socket by SocketId
//io.sockets.connected["socketid"].emit( 'new_count_message', {
io.sockets.connected[socketId].emit( 'new_count_message', {
new_count_message: data.new_count_message
});
//all sockets in a specific Room
//io.sockets.in("roomname").emit( 'new_count_message', {
io.sockets.in(user_id).emit( 'new_count_message', {
new_count_message: data.new_count_message
});
});
});
I'm new to socket.io, and I'm doing a simple API with NodeJS (express 4). I'm developing an action that is similar to the old "poke" action at facebook. A user send a poke to other user, and this one gets a notification on real time (this is the reason why I am using socket.io).
This is the code:
app.js
var port = 3000;
var app = module.exports = express();
var server = require('http').Server(app);
...
server.listen(port);
require('./config/socket-io')(app, server, secret);
socket-io.js
module.exports = function(app, server, secret) {
var clients = {};
console.log("initiating sockets...");
var sio = require('socket.io').listen(server, {'log level': 2});
sio.on('connection', function (socket) {
console.log("...new connection: "+socket.client.id);
clients[socket.id] = socket;
socket.emit('identification', { data : socket.client.id });
socket.on('newShoutOut', function(data) {
var receptor = data.idTo;
var emiter = socket.client.id;
console.log("...new shout out from " +emiter+ " to "+receptor);
sio.sockets.sockets[receptor].emit({ data : data.data, from : emiter });
});
socket.on('disconnect', function() {
console.log("..."+socket.client.id + " disconnected");
});
});
};
Here you can differentiate three states:
Connection: The server detects all the clients connection to the host:port. After that, the server sends to each client his ID. This works fine.
Send message: One client sends a notification to other client. For now, the server receives the notification from one client, but the "receiver" doesn't receive anything.
Disconnection: Doesn't matter in this case.
My question is, what is the way to send a message to a client directly knowing the ID? What I am doing wrong? I tried so many options to send a message directly to a specific client ID but didn't work...
EDIT
Frontend
var socket = io('http://localhost:3000');
var id = "";
socket.on('connection', function (data) {
console.log("connected!");
console.log(data);
});
socket.on('identification', function(data) {
id = data.data;
$("#socket_info h1").html("ID: "+id);
});
socket.on('newShoutOut', function(data) {
console.log("newShoutOut received!");
});
Ok, so I assume the shoutout is coming from a user? You will need to create the event on the clientside, such as:
var button = $('#button');
button.on('click', function() {
var msg = 'message',
userID = '123'; //get the ID who they are messaging
socket.emit('sendShoutOut', {msg: msg, id: userID});
});
Then you will need to receive that response on the server, and reply to the user in that function:
socket.on('sendShoutOut', function( data ) {
socket.sockets.sockets[data.id].emit('sendPrivateMsg', { data : data.msg, from : emiter });
});
Lastly, the reciever must be notified, so you will need to handle the response on the client:
socket.on('sendPrivateMsg', function( data ) {
alert(data);
});
Hope this helps.