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
});
});
});
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');
});
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.
I'm having problems with socket.io.
I try to create a single socket connection where this is connected to multiple rooms.
This is my current code:
function JoinRoom(id){
socket = io(domain);
socket.on('connect', function (data) {
console.log('Connected to ' + room);
socket.emit('room', room);
});
socket.on('message', function (data) {
console.log(data);
});
}
The problem is that if I remove the var socket.io(domain) function was not connected and do not receive data from the room.
Example:
socket = io(domain);
function JoinRoom(id){
socket.on('connect', function (data) {
console.log('Connected to ' + room);
socket.emit('room', room);
});
socket.on('message', function (data) {
console.log(data);
});
}
If I take the socket.io() function of the JoinRoom() function I do not receive messages message or anything. It does not work.
What am I doing wrong? Any solution?
On the client, create an event to indicate the access room.
On the server, apply the access logic.
Client
var socket = io('http://localhost');
function JoinRoom(data){
socket.emit("join", data);
}
var data = {
room:'ejemplo'
};
JoinRoom(data);
Server
var io = require('socket.io')(app);
io.on('connection', function(socket){
socket.on('join', function(data){
console.log(data); // data = { room: String, ...}
socket.join(data.room);
});
socket.on('leave', function(data){
socket.leave(data.room);
});
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.
I've successfully used nodejs and socket.io to send a large json file from a server to a client, but I'm stumped on the next step: I need to analyse the json, and only send changes to the client, so that I have very fast real-time updates on the client-side, without having to send the entire json every second. I fear I'm missing something really basic. It's currently sending the entire json over and over. I see where that's happening, I just don't see how to send, instead, only the CHANGES. Ideas?
Server:
/*************************** Require modules ********************************/
var app = require('express')()
, request = require('request')
, fs = require('fs')
, http = require('http')
, server = require('http').createServer(app)
, io = require('socket.io').listen(server);
/************************* Start socket server ******************************/
server.listen(8127);
// socket.io
io.sockets.on('connection', function(socket){
var options = {
host: 'host.com',
port: 80,
path: '/api/tomyjson.json',
headers: {
'Authorization': 'Basic ' + new Buffer('username' + ':' + 'password').toString('base64')
}
};
function getStreams() {
http.get(options, function(response){
var data = "";
response.on('data', function(chunk) {
data += chunk;
});
response.on('end', function() {
socket.emit('news', JSON.parse(data));
});
});
}
setInterval(getStreams, 5000);
socket.on('message', function(data){
console.log(data)
})
socket.on('disconnect', function(){
})
});
Client JS:
var socket = io.connect('host.com:8127/');
socket.on('news', function (json) {
$.each(json.data, function(i, x) {
console.log(x.json.element);
$('#stream-container').prepend(x.json.element);
})
socket.emit('my other event', { my: 'data' });
});
socket.on('message', function(data){
// Do some stuff when you get a message
oldData += data;
document.getElementById('stream-container').innerHTML = oldData;
});
socket.on('disconnect', function(){
// Do some stuff when disconnected
});