How to communicate simultaneously in both ways on socket.io node.js - node.js

I want to send some data to a node.js server when some event triggers. In parallel, the server is supposed to send some data every 1 second to the client. I am using socket.io for this. Here is my code:
Server side:
app= require('http').createServer(handler).listen(3000),
io = require('socket.io').listen(app);
// request handler function, will send client file which include sliders and graph
function handler (req, res) {
var reqObj = urr.parse(req.url, true);
var reqPath = reqObj.pathname;
if ('/' == reqPath ) {
res.writeHead(200, {'Content-Type': 'text/html'});
fs.readFile(__dirname + '/client.html', function(err, data) {
if (err) {
res.writeHead(500);
return
res.end('Errorloadingclient.html'); }
res.end(data);
}); } };
var slider1, slider2, slider3, slider4 ;
io.sockets.on('connection', function(socket) {
// receive changed value of slider send by client
socket.on('ValSlider1', function(data){
slider1 = data ;
console.log("Slider 1 Value: " + data); });
// same for three more sliders });
// send received values back to client after every 1 second interval
setInterval(function () {
var data = slider1 + "-" + slider2 + "-" + slider3 + "-" + slider4;
socket.emit('packet', data);
},1000); });
app.maxConnections = 1;
Client side:
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script type="text/javascript"
src="http://smoothiecharts.org/smoothie.js"></script>
// slider
<p id="ValSlider1"> Curr Val </p>
<input class = "mySlider1" type="range" name="slider" id="slider-0" value="0" min="0" max="100" />
// similar for three more sliders
Packet
var socket = io.connect('http://localhost');
// send changed value to server
$(".mySlider1").change(function() {
var sVal = $(this).val();
socket.emit('ValSlider1', sVal);
});
// similar for three more sliders
socket.on('packet', function (data) {
var valFromServer = data.split('-');
document.getElementById("ValSlider1").innerHTML = valFromServer[0];
});
</script>
Now, I get data on the server side only when I use 'socket.emit()' twice in the client, where the server sends data at 1 second intervals.

finally i manage to do it in this way,
On server side
app= require('http').createServer(handler).listen(3000),
io = require('socket.io').listen(3001);
publisher = require('socket.io').listen(app);
On client side
var socket = io.connect('http://localhost:3001');
var socket2 = io.connect('http://localhost');
client will send data to server on 'socket', in response server will also send some data on same port. simultaneously, server will publish data on 3001 port at every 1 second interval which is received in client on ".on('data')" event of server1.

Related

socket.broadcast.to(receiver_socket_id) emitting n number of data (instead of one) to the receiver, where n is the number of user connected

I am using socket.io for private chatting for the server side I am using
socket.broadcast.to(receiver_socket_id).emit('message', data); // where data is a json object containing text
And at the client side code I catch the data using
socket.on('message', function (data) {
alert(data. text);
});
Its working properly and showing the alert on that specific user (socket id) ‘s panel when only two socket are connected (sender and receiver). But the problem appears when one more user connects to that socket then I see two alerts and when total 4 user connected (sender + receiver + two others) then see 3 alerts. But the good point is I can see the alerts only that specific client's panel not the others.
I can’t understand the problem, please help.
Please have a look on it
gyazo.com/a98d3a64a9fc6487e6ded8ccd90fd5ab
it prints test three times because three browsers are opened.
Full code here:
Sever side (I have used Redis):
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var redis = require('redis');
server.listen(8080);
var usernames = {};
io.on('connection', function (socket) {
console.log(socket.id);
socket.on('adduser', function (userId) {
usernames[userId] = socket.id;
});
var redisClient = redis.createClient();
redisClient.subscribe('message-channel');
redisClient.on('message', function (channel, data) {
var jsonObj = JSON.parse(data);
var rcvrId = jsonObj.rcvrId;
socket.broadcast.to(usernames[rcvrId]).emit('message', data); // Not throwing error....should work
});
socket.on('disconnect', function () {
console.log(socket.id + ' Disconnected');
redisClient.quit();
});
});
Client side:
var socket = io.connect('http://localhost:8080');
var userId = $('input[name="userId"]').val();
var rcvrId = $('input[name="rcvrId"]').val();
socket.on('connect', function () {
// call the server-side function 'adduser' and send one parameter (value of prompt)
socket.emit('adduser', userId);
});
socket.on('message', function (data) {
data = jQuery.parseJSON(data);
console.log(data);
$("#messages").append("<div><strong>" + data.userId + " : </strong><span>" + data.message + "</span></div>");
});
You can use io.of('/').sockets[rcvrId].emit('message', data). In case you are using a different namespace just replace the / with your namespace.

In Node.js how to send message to client side from a handler/callback method

I am a beginner in node.js. I am trying to create a webapp using node.js which will create servers in cloud and manage them. After doing some research I've decided to use node.js, socket.io, express and pkgcloud modules to create the webapp. Now, the problem I am facing is that I am unable to send messages to the front-end/client-side when a server is getting created. The server is getting created successfully but I am not getting how to send the server status to the browser screen.
Here's the code:
index.js
var express = require('express'),
app = express();
app.use(express.static(__dirname + '/'));
var io = require('socket.io').listen(app.listen(1337));
io.sockets.on('connection', function(socket) {
socket.on('mesg_to_server', function(data) {
// This is for testing whether we're receiving msgs on client side
io.sockets.emit("mesg_to_client",{ mesg: data["mesg"], mesg1: data["mesg1"] });
var Rackspace = require('./ex_rackspace');
var rackspace = new Rackspace();
rackspace.create(data.mesg);
});
});
ex_rackspace.js:
var pkgcloud = require('pkgcloud'),
_ = require('./node_modules/pkgcloud/node_modules/underscore');
var client = pkgcloud.providers.rackspace.compute.createClient({
username: 'xxxx',
apiKey: 'xxxxx',
region: 'HKG'
});
// This function will handle our server creation,
// as well as waiting for the server to come online after we've
// created it.
function handleServerResponse(err, server) {
if (err) {
console.dir(err);
return;
}
console.log('SERVER CREATED: ' + server.name + ', waiting for active status');
// Wait for status: ACTIVE on our server, and then callback
server.setWait({ status: server.STATUS.running }, 5000, function (err) {
if (err) {
console.dir(err);
return;
}
console.log('SERVER INFO');
console.log(server.name);
console.log(server.status);
console.log(server.id);
console.log('Make sure you DELETE server: ' + server.id +
' in order to not accrue billing charges');
});
}
var Rackspace = function() {
};
Rackspace.prototype.test = function (text) {
console.log("provider: Rackspace: " + text);
}
// first we're going to get our flavors
Rackspace.prototype.create = function (server) {
client.getFlavors(function (err, flavors) {
if (err) {
console.dir(err);
return;
}
// then get our base images
client.getImages(function (err, images) {
if (err) {
console.dir(err);
return;
}
var flavor = _.findWhere(flavors, { name: '1 GB Performance' });
var image = _.findWhere(images, { name: 'CentOS 5 (PV)' });
// Create our first server
client.createServer({
name: server,
image: image,
flavor: flavor
}, handleServerResponse);
});
});
}
module.exports = Rackspace;
page.html (client-side):
<!DOCTYPE html>
<html>
<head>
<script src="/socket.io/socket.io.js"></script>
<script type="text/javascript">
// our socket.io code goes here
var socketio = io.connect("127.0.0.1:1337");
socketio.on("mesg_to_client", function(data) {
document.getElementById("chatlog").innerHTML = ("<hr/>" +
data.mesg + ' ' + data.mesg1 + document.getElementById("chatlog").innerHTML);
});
socketio.on("test_output", function(data) {
console.log(data.mesg);
});
function sendMessage() {
var msg = document.getElementById("mesg_input").value;
socketio.emit("mesg_to_server", { mesg : msg, mesg1 : "here"});
}
</script>
</head>
<body>
<input type="text" id="mesg_input"/>
<button onclick="sendMessage()">Create</button>
<div id="chatlog"></div>
</body>
</html>
You need to add a callback to the create function
Rackspace.prototype.create = function (server, callback){
//your code - if err send error else send success message
callback(err, message)
}
Then use it when you call create
rackspace.create(data.mesg, function (err, message){
//your code with your socket emit here
});

Server client communication Node.js

I have written a server program server.js as below
var SerialPort = require("serialport").SerialPort
var io = require('socket.io').listen(80);
var serialPort = new SerialPort("COM4", {
baudrate: 9600
});
serialPort.on("open", function () {
console.log('open');
serialPort.on('data', function(data) {
console.log('data received: ' + data);
});
serialPort.write("ls\n", function(err, results) {
console.log('err ' + err);
console.log('results ' + results);
//io.sockets.emit('message', 'data');
});
});
io.sockets.on('connection', function (socket) {
// If socket.io receives message from the client browser then
// this call back will be executed.
socket.on('message', function (msg) {
console.log(msg);
});
// If a web browser disconnects from Socket.IO then this callback is called.
socket.on('disconnect', function () {
console.log('disconnected');
});
});
var cleanData = ''; // this stores the clean data
var readData = ''; // this stores the buffer
serialPort.on('data', function (data) { // call back when data is received
readData += data.toString(); // append data to buffer
// if the letters 'A' and 'B' are found on the buffer then isolate what's in the middle
// as clean data. Then clear the buffer.
if (readData.indexOf('B') >= 0 && readData.indexOf('A') >= 0) {
cleanData = readData.substring(readData.indexOf('A') + 1, readData.indexOf('B'));
readData = '';
io.sockets.emit('message', cleanData);
}
});
The client side program is (index.html)
<html>
</head>
<link type="text/css" href="/css/smoothness/jquery-ui-1.8.20.custom.css" rel="Stylesheet" />
<script type="text/javascript" src="//localhost:8000/socket.io/socket.io.js"></script>
<script type="text/javascript" src="/js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="/js/jquery-ui-1.8.20.custom.min.js"></script>
<script>
var socket = io.connect('http://localhost:8000');
socket.on('connect', function () {
socket.on('message', function (msg) {
// Convert value to integer
var val = ((parseInt(msg) / 1023)*100);
// Put sensor value to the 'sensor_value' span
$('#sensor_value').html(val);
});
});
});
</script>
</head>
<body>
<div role="main">
Potentiometer Value: <span id="sensor_value"></span><br/>
</div>
</body>
</html>
I am using WAMP as web server
The server console is giving me the required output. But nothing is coming in the webpage index.html
Here you can find a tutorial showing exactly what you're trying to do: create a Node.js server and forwarding data from serial port to an html page via Websockets.
It was very useful to me when doing the same, sure it will help.

NodeJS and socket.io chat customization

I have a basic chat system working with NodeJS, express, and socket.io. Now I want to have the server insert the date into the chat stream every 5 seconds. Since this isn't initiated by the user, I am having trouble with the basic request. I am new to NodeJS and maybe it is just a syntax thing that I don't understand. Anyways, with this current code, the date only gets inserted after someone sends a chat message through. I want this to happen automatically on the server side. If no one is chatting, the date will still come through to the client every 5 seconds. My problem most likely stems from the comment section title: "How do I get my periodic timer in here..." Instead I am trying to insert it at the bottom where it says - "//***This section sends out the notification..." Do I structure the functions differently or something? Thanks in advance.
Server.js
var express = require('express'),
app = express()
, http = require('http')
, server = http.createServer(app)
, io = require('socket.io').listen(server);
// listen for new web clients:
server.listen(8080);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
app.get('/sio/socket.io.js', function (req, res) {
res.sendfile('/root/nodejs/node-v0.10.0/node_modules/socket.io/lib/socket.io.js');
});
//How do I get my periodic timer in here so it can send the date every 5 seconds?
io.sockets.on('connection', function (socket) {
socket.on('sendMessage', function (data) {
socket.broadcast.emit('message', data);
socket.emit('message', { text: '<strong>'+data.text+'</strong>' });
});
});
// Periodic Running
var coolerInterval = function(func, interval, triggerOnceEvery) {
var startTime = new Date().getTime(),
nextTick = startTime,
count = 0;
triggerOnceEvery = triggerOnceEvery || 1;
var internalInterval = function() {
nextTick += interval;
count++;
if(count == triggerOnceEvery) {
func();
count = 0;
}
setTimeout(internalInterval, nextTick - new Date().getTime());
};
internalInterval();
};
coolerInterval(function() {
showdate = new Date().getTime();
console.log( showdate );
//Go ahead and send a notification to everyone.
//***This section sends out the notification that a pick was made
io.sockets.on('connection', function (socket) {
socket.on('sendMessage', function (data) {
socket.broadcast.emit('message', showdate);
});
});
//***End sending out notification.
}, 1000, 5);
//End Periodic
Here is the html in the browser - index.html
<html>
<body>
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
var socket = io.connect('http://dev.mysite.com:8080');
socket.on('message', function (data) {
$('#chat').append(data.text + '<br />');
});
$('#send').click(function () {
socket.emit('sendMessage', { text: $('#text').val() });
$('text').val('');
});
});
</script>
<div id="chat" style="width: 500px; height: 300px; border: 1px solid black">
</div>
<input type="text" name="text" id="text">
<input type="button" name="send" id="send" value="send">
</body>
</html>
It's much simpler than you're making it. You can just setInterval() to 5 seconds, and call io.sockets.emit(), which will send the message to all connected sockets.
setInterval(function() {
io.sockets.emit('message', (new Date()).getTime());
}, 5000);
Do this on line 18, and delete everything below there.

How to update the client HTML page according to the nodejs server outputs?

I developed an app using namespaces of nodejs where a client (client1) sends the data to the server, and the server sends the same data to another client (client2).
Everything is working fine, except that the data is rendered in client2 only if i refresh the page.. How to update the data dynamically?
the codes are as following:
server::
var io = require('socket.io').listen(8007);
var chat = io
.of('/chat')
.on('connection', function (socket) {
socket.on('message', function(message){
console.log("Received message:: " + message + " - from client " + socket.id);
var news = io
.of('/news')
.on('connection', function (socket1) {
socket1.send("received::" + message + " - from client " + socket.id);
});
});
});
and the client1 is::
<script>
var count=0;
function connect() {
var chat = io.connect('http://localhost:8007/chat');
chat.send('chat message:::' + count);
count++;
}
</script>
receiving client being::
<script>
var news = io.connect('http://localhost:8007/news');
news.on('message', function(data){
document.getElementById('message').innerHTML = "\n Server says: " + data;
});
</script>
I think your problem is on the server. You aren't setting up your "news" listener until after you receive a connection to "chat". Change your server code to something like the following:
var io = require('socket.io').listen(8007);
var newsSocket;
var news = io
.of('/news')
.on('connection', function (socket1) {
newsSocket = socket1;
});
var chat = io
.of('/chat')
.on('connection', function (socket) {
socket.on('message', function(message){
console.log("Received message:: " + message + " - from client " + socket.id);
for(var i=0; i<newsSockets.length; i++) {
newsSocket.send("received::" + message + " - from client " + socket.id);
}
});
Note: This will only send the news message to the last client that connected. You should have a collection(array) of news connections. You should also remove them when they disconnect.

Resources