socket.io get data from onclick action then pass the data to other pages to execute the data - node.js

I want to create a page using node.js and socket.io.
There are two buttons inside the page, when I click one of them, it will change a variable which defines the animation-duration(I omit the CSS animation codes here).
When I open the same page on another web-browser and click one of the buttons, I hope to see the change in both of the webpages. I don't know how to write the code inside the socket.on('chat', function(data){???}); to make two pages communicate with each other.
Client side:
//socket.io codes--
<script type="text/javascript" charset="utf-8">
var socket = io.connect('http://localhost:3000');
socket.on('chat', function (data)
{
function change_position(data)
{
document.getElementById("animation1").style.WebkitAnimationDuration=data;
}
});
</script>
.....
//action--
<body>
<button id="1b" type="button" style="position:absolute; left:377px; top:220px;" value="2s"; onclick="change_position(value)"> - 1 - </button>
<button id="2b" type="button" style="position:absolute; left:477px; top:220px;" value="15s"; onclick="change_position(value)"> - 2 - </button>
</body>
server side:
var io = require('socket.io'),
connect = require('connect');
var app = connect().use(connect.static('public')).listen(3000);
var chat_room = io.listen(app);
chat_room.sockets.on('connection', function (socket) {
socket.on('chat', function (data) {
chat_room.sockets.emit('chat', data);
});
});

If your want a message to propagate to all clients/sockets, in your server you should have something like:
chat_room.sockets.on('connection', function (socket) {
socket.on('chat', function (data) {
socket.broadcast.emit('chat', data);
socket.emit('chat',data);
});
});
The line socket.emit('chat',data); allows you to send the message back also to the sender of it, because broadcast will send it all other sockets.
Of course, you could ommit that line and handle the message sending logic in the client; i.e. adding some JavaScript code that makes the changes you want just after sending the message to the server.

You can emit on your client using socket.emit('message', data). Then on the server get it with chat_room.socket.on('message', data). Emit it to the clients using chat_room.sockets.emit('message', data).

Related

I cannot connect to a sites socket

I've been trying to do this but can you connect to another websites their socket.io server? I've been trying to scrape data from a website that uses socket.io for live updates. It would be very handy if this were to be possible.
I'm trying to get live updates from the website https://www.ethercrash.io/ - However I tried the following code and wouldn't get any updates other than a connection;
var io = require('socket.io-client');
var socket = io('https://www.ethercrash.io')
socket.on('connect', function(){
console.log(true);
});
socket.on('msg', function(data) {
console.log('chat message');
});
socket.on('disconnect', function(){
console.log(false);
});
Am I doing something wrong or is this just not possible?
I use the following in all my node.js / express / socket.io projects. Hopefully it helps you out.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>
<script>
$(document).ready(function() {
// NOTE, I AM FORCING WEBSOCKET TRANSPORT HERE. AND AM NOT ALLOWING
// SOCKET.IO TO FALL BACK TO LONG POLLING FALLBACK,
// SO YOU CAN REMOVE THE TRANSPORTS AND GO WITH SOCKET.IO DEFAULTS
// PORT I'M USING IS 3000 -- SO THE PORT CAN BE IMPORTANT, DEPENDING ON YOUR USASGE
var socket = io.connect("https://MY-SERVER-NAME-HERE.eastus.cloudapp.azure.com:3000", {
secure: true,
transports: ["websocket"],
path: "/socket/socket.io"
});
// EVERY TIME THE NODE.JS SERVER SENDS US 'MESSAGE' WE'LL DISPLAY THAT UPDATED NUMBER IN A DIV
socket.on("message", function(msg) {
document.getElementById("message").innerHTML = msg;
});
});
</script>
</head>
<body style="width: 100%;">
<div id="message" style="text-align: center; width: 100%; font-size: 2em;"></div>
</body>
</html>
You also are depending on that 'other site' (running the socket server) emitting out to either ALL connected clients or to your connection specifically. Unless either of those happen, you will only have a connection with no messages being emitted out (to be read / parsed).
Sockets are really fun to work with and full of potential once you get the hang of it!

Use the same socket.io connection in multiple HTML pages in node js

-Follwing is the jquery code I have written in my (dashboard.html) file
<script>
$(function(){
$("#username").hide();
var socket= io.connect();
$(document).on("click", ".help", function () {
alert( $(this).attr('id'));
socket.emit('help',{helper:$username.val(),requester:$(this).attr('id')});
});
});
---On clicking help button socket will emit an event "help" as you can see in the code.
---Following is the app.js file on server
io.sockets.on('connection',function(socket){
socket.on('help',function(data){
console.log('rohi is goood',data.helper);
socket.emit('loadList' , {helper:data.helper,requester:data.requester});
});
});
---On "help" event socket is emitting an event "loadList" in app.js file.
Now I want to use "loadList" event in some other html file like "chat.html".
The code I have written is as follows for chat.html.
<script>
$(function(){
// var socket= io.connect();
// var socket= io.connect('http://localhost:3000/', { 'force new //connection': true });
socket.on('loadList',function(data){
alert('inside help',$('#usernam').val());
console.log('tatai',$('#usernam').val());
if($('#usernam').val()== data.helper){
$('#chatList').append('<p>'+data.requester+'</p>'+'<button value="chat"></button>');
}
else if($('#usernam').val() == data.requester){
$('#chatList').append('<p>'+data.helper+'</p>'+'<button value="chat"></button>');
}
else {
alert('fuck off');
}
});
The above code is not working. Please tell me how can I use same socket connection in the chat.html file.(loadList event is not working).
As your question is not complete so i am assuming you want to know if socket.io connection can be used on different html pages . Yes you can access it on every html page of your application as long as you have one server on which socket.io is used .
Every time a new user comes a socket session is created for that particular user and that user can access any page of your application .

Chat App using Socket.io and Node.js

I am developing chat app using Node.js and Socket.io.
Here is my code.|
socket.js
var io = require('socket.io').listen(8001);
var http = require('http');
var url = require('url');
var fs = require('fs');
// open the socket connection
io.sockets.on('connection', function (socket) {
// listen for the chat even. and will recieve
// data from the sender.
socket.on('chat', function (data) {
// default value of the name of the sender.
var sender = 'unregistered';
// get the name of the sender
socket.get('nickname', function (err, name) {
console.log('Chat Message By: ', name);
console.log('error ', err);
sender = name;
});
// broadcast data recieved from the sender
// to others who are connected, but not
// from the original sender.
socket.broadcast.emit('chat', {
msg : data,
msgr : sender
});
});
// listen for user registrations
// then set the socket nickname to
socket.on('register', function (name) {
// make a nickname paramater for this socket
// and then set its value to the name recieved
// from the register even above. and then run
// the function that follows inside it.
socket.set('nickname', name, function () {
// this kind of emit will send to all! :D
io.sockets.emit('chat', {
msg : "Hello " + name + '!',
msgr : "Mr.Server"
});
});
});
});
index.html
<html>
<head>
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script>
var name = '';
var socket = io.connect('http://localhost:8001');
// at document read (runs only ones).
$(document).ready(function(){
// on click of the button (jquery thing)
// the things inside this clause happen only when
// the button is clicked.
$("button").click(function(){
// just some simple logging
$("p#log").html('Sent message: ' + $("input#msg").val());
// send message on inputbox to server
socket.emit('chat', $("input#msg").val() );
$("p#data_recieved").append("<br />\r\n" + name + ': ' + $("input#msg").val());
// then we empty the text on the input box.
$("input#msg").val('');
});
$("#btnSubmit").click(function(){
alert("Disconnected");
//socket.clients[kickedUserSocketId].onDisconnect();
socket.close();
});
// ask for the name of the user, ask again if no name.
while (name == '') {
name = prompt("What's your name?","");
}
// send the name to the server, and the server's
// register wait will recieve this.
socket.emit('register', name );
});
// listen for chat event and recieve data
socket.on('chat', function (data) {
// print data (jquery thing)
$("p#data_recieved").append("<br />\r\n" + data.msgr + ': ' + data.msg);
// we log this event for fun :D
$("p#log").html('got message: ' + data.msg);
});
socket.emit('forceDisconnect');
</script>
</head>
<body>
<input type="text" id="msg"></input>
<button>Click me</button>
<p id="log"></p>
<p id="data_recieved"></p>
</body>
<input id = "btnSubmit" type="submit" value="Disconnect"/>
</html>
I am running first socket.js from command prompt. After that, I am running .html file in browser 2 times. Now 2 users can chat via browsers. But when I am trying to put my .js file and .html file on server which I have created using FileZila and running .js file, it is running but when I am trying to run .html file on server side(In this case FileZila) , by giving the IP address and Port number of server it is not running. Can you tell me what is the problem?
This doesn't seem to be a nodejs-issue.
You have a server that should be reachable by IP with something like 'http://your.domain.or.ip:80'.
If you get a "can't connect" in your browser then make sure there is no firewall in its way and that port (in the example: 80) is reachable from your browser location (aka known as "your pc"). Please note that you have your socket-service on port 8001 and your web server maybe runs on a different port? Make sure both ports are open.
If you get a blank page, check the browser javascript error messages.
There is a chance that you forgot to upload the file 'socket.io.js' in that directory '/socket.io/'. Try to download that file directly to see if your server serves.

Redis pub/sub for chat server in node.js

I'm trying to work the Redis Cookbook example:
var http = require('http'),
io = require('socket.io')
fs = require('fs'),
redis = require('redis'),
rc = redis.createClient(9189, "pike.redistogo.com");
rc.auth("passwd", function() {
console.log("Connected! to redistogo!");});
rc.on("connect", function() {
rc.subscribe("chat");
console.log("rc connect event");
});
I am successful through here but never get "message."
rc.on("message", function (channel, message) {
console.log("Sending: " + message);
socketio.sockets.emit('message', message);
});
webpage = http.createServer(function(req, res){
console.log('webpage request starting...');
fs.readFile('./index.htm', function(error, content) {
if (error) {
res.writeHead(500);
res.end();
}
else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(content, 'utf-8');
}
});
});
webpage.listen(7777);
my client side index.htm is this
<!docttype html>
<html lang="en">
<head>
<script src ="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"> </script>
<script src="http://www.heaphash.com:7777/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('www.heaphash.com', { port: 7777});
socket.on('message', function(data){
var li = new Element('li').insert(data);
$('messages').insert({top: li});
}
</script>
<meta charset="utf-8">
<title>Chat with Redis</title>
</head>
<body>
<ul id="messages">
<!-- chat messages go here -->
</ul>
<form id="chatform" action="">
<input id="chattext" type="text" value="" />
<input type="submit" value="Send" />
</form>
<script>
$('#chatform').submit(function(){
socket.emit('message', $('chattext').val());
$('chattext').val(""); //cleanup the field
return false;
});
</script>
</body>
</html>
how does a client publish to a specific Redis "chat" channel.
If you are using redis pub/sub functionality within your node.js program you should dedicate one redis client connection for listening on some channel and second redis client connection for sending normal commands and/or publishing messages to your channel(s). From node_redis docs:
When a client issues a SUBSCRIBE or PSUBSCRIBE, that connection is put
into "pub/sub" mode. At that point, only commands that modify the
subscription set are valid. When the subscription set is empty, the
connection is put back into regular mode.
If you need to send regular commands to Redis while in pub/sub mode,
just open another connection.
Your problem is also related to these questions:
Redis / Node.js - 2 clients (1 pub/sub) causing issues with writes
Why can't I have a single Redis client acting as PUB and Sub in the same connection?
I believe that the example from that book is missing something, I also read that book and wondered. You are subscribed to the Redis channel and are waiting for messages on the server side, but you never publish to that channel. What is missing is an event listener so when there is a websocket message, you publish that message to the redis channel.

Sending message to specific client with socket.io and empty message queue

I´m going crazy with socket.io!
Documentation is so bad it's simply not true.
I want to send a feedback to specific client over socket.io
My server side looks like this:
app.get('/upload', requiresLogin, function(request, response) {
response.render('upload/index.jade');
io.sockets.on('connection', function (socket) {
console.log('SOCKET ID ' + socket.id);
io.sockets.socket(socket.id).emit('new', 'hello');
});
});
and the client side looks like this:
$(document).ready(function() {
var socket = io.connect('http://localhost:80/socket.io/socket.io.js');
socket.on('new', function (data) {
console.log(socket.id);
console.log(data);
//$('#state').html(data.status);
});
});
but the client does simply nothing. I have tried nearly everything. Can someone tell me what I am doing wrong, please! :(
to send a message to a specific client save every one that connects to the server in an Object.
var socketio = require('socket.io');
var clients = {};
var io = socketio.listen(app);
io.sockets.on('connection', function (socket) {
clients[socket.id] = socket;
});
then you can later do something like this:
var socket = clients[sId];
socket.emit('show', {});
A couple of ways to send feedback to a specific client over socket.io include:
As stated by pkyeck, save all clients to an Object, so you can send to these specific clients later in your route handlers, e.g.:
var sessionsConnections = {};
sio.on('connection', function (socket) {
// do all the session stuff
sessionsConnections[socket.handshake.sessionID] = socket;
});
or, use socket.io's built in support for rooms - subscribe each client to a room on connection and send via this room within route handlers, e.g.:
sio.on('connection', function (socket) {
// do all the session stuff
socket.join(socket.handshake.sessionID);
// socket.io will leave the room upon disconnect
});
app.get('/', function (req, res) {
sio.sockets.in(req.sessionID).send('Man, good to see you back!');
});
Acknowledgement:
http://www.danielbaulig.de/socket-ioexpress/#comment-1158
Note that both these example solutions assume that socket.io and express have been configured to use the same session store and hence refer to the same session objects. See the links above and below for more details on achieving this:
https://github.com/LearnBoost/socket.io/wiki/Authorizing
2 things
1) You should really place your io.sockets.on(..) outside your app/update route to prevent adding multiple listeners for clients.
2) io.sockets.socket(id); should not be used, it should have been socket.emit('new', 'hello')
In socket.io 1.0, this is how it would work. It may work for lower versions, but I cannot guarantee it.
socket.to(socket_id_here).emit('new', 'hello');
This works because socket.io automatically adds a socket to a room with the socket's id on connection.
Also, if you plan to upgrade to version 1.0, there are a lot of changes to the api, so you'll sometimes have to change some code to make it work in 1.0.
The correct way to do this in Socket.io 1.0+ is:
io.to(users_socket_id).emit('new', 'hello');
You can also substitute a room name for 'users_socket_id' to emit to a specific socket.io room.
First of all, you cannot use socket.id on client side.
And then change the line
var socket = io.connect('http://localhost:80/socket.io/socket.io.js');
to
var socket = io.connect('http://localhost:80/');
I believe io.sockets.socket has been removed and has been a problem in Socket.IO (https://github.com/socketio/socket.io/issues/1618).
You can use io.sockets.connected[socket.id] and store the socket.id to reference with the user via username:
var usernames = {};
usernames[username] = socket.id;
// Sending the message
io.sockets.connected[usernames[username]].emit(...);
I don't see it anywhere on the documentation so I can see how this hasn't been answered. Also, if you don't have any reference via usernames, you can instead try:
users[socket.id] = socket.id;
to duplicate the key and value for easy access.
There is also possibly another way by using io.clients as described below, but I haven't used that method.
OTHER SOLUTION: Send message to specific client with socket.io and node.js
Have you tried using?
var socket = io.connect('http://localhost:80/');
i tired with the latest version of node and socket.io
below i am going to post complete code
<ul id="messages"></ul>
<form action="">
<input id="id1" /><button>Send</button>
</form>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var io = io.connect();
$('form').submit(function(){
io.emit('drumevent', $('#id1').val());
$('#id1').val('');
return false;
});
io.on('drumevent', function(msg){
console.log(msg);
$('#messages').append($('<li></li>').text(msg.message+' quantity = '+msg.quantity));
});
</script>
server side code
var usernames = {};io.on('connection', function(socket){usernames["username"] = socket.id;
socket.on('drumevent', function(msg){
var socketId = socket.id;io.to(socketId).emit('drumevent', data);

Resources