Sending messages to all browsers with socket io - node.js

I am messing around with socket.io and node.js, and was wondering how to accomplish the following: I have a simple form that sends a text string to the server, and the server sends it back, and it gets appended to a div. what I would like to do is have that div update for all users in all browsers, currently it only updates the one that the message was sent from.
code from app.js (node.js server) :
io.sockets.on('connection', function(socket) {
socket.on('send_message', function(data) {
data.message = data.message + ' yo<br/>';
socket.emit('get_message',data);
});
});
code on client-side:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
$(document).ready(function() {
var socket = io.connect('http://localhost:3000');
$('#sender').live('click',function() {
var user_message = $('#message_box').val()
socket.emit('send_message',{message: user_message});
});
socket.on('get_message', function(data) {
$('#data').append(data.message);
});
});
</script>
and the html:
<div id='data'></div>
<input type='text' id='message_box' placeholder='send message'>
<button id='sender'>Send Message</button>
what should I be doing to send messages to multiple browsers?

Change
socket.emit('get_message',data);
To
socket.broadcast.emit('get_message',data);
To broadcast it to all connected users, except to the socket where you are calling the broadcast on.
If you also want to include that socket you can do
io.sockets.emit('get_message', data);

Related

new relic web transaction appearing under root

I am using the node.js agent for the new relic. I am using Node.js custom instrumentation to monitor socket.io, new relic web transaction appearing under root and no data is visible as I am not able to monitor socket.io. Below is the output under Transaction Root Path
Breakdown table
Category Segment % Time Avg calls (per txn) Avg time (ms)
WebTransaction Root path 100.0 1.0 2,150
Server Code
var http = require('http'),
fs = require('fs'),
nr = require('newrelic'),
index = fs.readFileSync(__dirname + '/sock_client.html');
var app = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(index);
});
// Socket.io server listens to our app
var io = require('socket.io').listen(app);
// Send current time to all connected clients
function sendTime() {
io.emit('time', { time: new Date().toJSON() });
}
// Send current time every 10 secs
setInterval(sendTime, 10000);
// Emit welcome message on connection
io.on('connection', function(socket) {
// Use socket to communicate with this particular client only, sending it it's own id
socket.emit('welcome', { message: 'Welcome!', id: socket.id });
socket.on('rings', function(data){
nr.startWebTransaction('websocket/ping/test_v3', function transactionHandler() {
socket.emit('pong', { message: 'Welcome!' });
console.log(data);
nr.addCustomParameters({
"Discount Code": "Summer Super Sale",
"Item Code": 31456
});
});
});
socket.on('pings', function(data){
nr.startWebTransaction('websocket/ping/test_v5', function transactionHandler() {
let trans = nr.getTransaction();
someAsyncBeha("console.log", function(){
trans.end();
})
console.log(data);
});
});
});
function someAsyncBeha(data, cb){
setTimeout(function() {
console.log("Goodbye!");
console.log(data);
cb();
}, 5000);
};
Client Code
<!doctype html>
<html>
<head>
<link rel="shortcut icon" href="/favicon.png">
<script src='/socket.io/socket.io.js'></script>
<script>
var socket = io();
socket.on('welcome', function(data) {
addMessage(data.message);
// Respond with a message including this clients' id sent from the server
socket.emit('rings', {data: 'foo!', id: data.id});
});
socket.on('time', function(data) {
addMessage(data.time);
socket.emit('pings', {data: 'foo!', id: data.time});
});
socket.on('error', console.error.bind(console));
socket.on('message', console.log.bind(console));
socket.on('pong', console.log.bind(console));
function addMessage(message) {
var text = document.createTextNode(message),
el = document.createElement('li'),
messages = document.getElementById('messages');
el.appendChild(text);
messages.appendChild(el);
}
</script>
</head>
<body>
<ul id='messages'></ul>
</body>
</html>
The issue was in the new relic module version, there are two suggestions.
First, upgrade the Node.js agent to v2.2.0
This version includes a bug fix that should resolve the issue you're seeing.
Second, move nr = require('newrelic'); to the top of the requires.
This ensures the agent catches everything in your application before the code has a chance to spin up. Without this, the code in the other requires can launch before the agent has a chance to inject its methods, resulting in no tracking for those methods.

Reaching a server from outside the network

I recently tried to run a nodejs chat demo and test it. It worked on the same computer as the program were running on, but the chat couldn't be reached from outside. This is the code for the server:
var WebSocketServer = require('ws').Server
var wss = new WebSocketServer({host: 'put_my_ip_in_here',port: 8000});
wss.on('connection', function(ws)
{
console.log('client connected...');
ws.on('message', function(message)
{
console.log('received from client: ' + message);
ws.send('received from server: ' + message);
});
});
I unblocked the port 8000 (udp and tcp as in my router and my firewall and told someone from outside my network to open the following page
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
function connect()
{
var socket = new WebSocket("ws://put_my_ip_in_here:8000");
socket.onopen = function() { message('Socket Status: '+socket.readyState+' (open)'); }
socket.onmessage= function(msg) { message('received: '+msg.data); }
function send()
{
var text = $('#text').val();
socket.send(text);
message('sent : '+text)
$('#text').val("");
}
{
$('#Log').append(msg+'</br>');
}
$('#text').keypress(function(event)
{
if (event.keyCode == '13')
{
send();
}
});
}
connect();
});
</script>
</head>
<body>
<div id="container">
<div id="Log"></div>
Input: <input id="text" type="text" />
</div>
</body>
</html>
But my computer/the chat wasnt reachable :c
Where is the problem? The demos seems to be running fine!

Socket.io : very strange

I try to make a chat with node.js and socket.io but I tried since 6 hours to resolve my problem but I don't succeed.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Socket.io</title>
</head>
<body>
<h1>Communication avec socket.io !</h1>
<div id="formulaire">
<form action="" method="post" id="form">
<input type="text" id="pseudo" placeholder="Pseudo"/>
<input type="text" id="message" placeholder="Message"/>
<input type="submit" value="Envoi"/>
</form>
</div>
<div id="wrapper">
Texte par défaut
</div>
<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
var socket = io.connect('http://localhost:8080');
$("#formulaire").submit(function() {
var pseudo = $("#pseudo").val();
var message = $("#message").val();
alert(pseudo = " " + message);
socket.emit("pseudo", pseudo);
socket.emit("message", message);
});
socket.on("message", function (message) {
alert("bien récupéré depuis serveur: " + message); //It works
var wrapper = document.getElementById('wrapper');
wrapper.innerHTML = "Le message est: " + message; //It doesn't work ?????
});
</script>
</body>
</html>
app.js
var http = require("http");
var fs = require("fs");
// Serving index.html to the client
var server = http.createServer(function(req, res) {
fs.readFile("./index.html", "utf-8", function(error, content) {
res.writeHead(200, {"Content-Type": "text/html"});
res.end(content);
});
});
// Loading socket.io
var io = require("socket.io").listen(server);
// Logging in console when a client connects
io.sockets.on("connection", function (socket) {
//socket.emit("message", "A new client has connected");
socket.on("pseudo", function(pseudo) {
console.log(pseudo);
socket.emit("pseudo", pseudo);
});
socket.on("message", function(message) {
console.log(message);
socket.emit("message", message);
});
});
server.listen(8080);
I don't understand because the alert gets opened with the variable from the server message but innerHTML doesn't get filled.
Because pseudo and message are input fields in a form, by default, the page get's reloaded because you click a submit button. To prevent this, you need to put return false; at the end of the submit handler, like this:
$("#formulaire").submit(function() {
var pseudo = $("#pseudo").val();
var message = $("#message").val();
console.log(pseudo = " " + message);
socket.emit("pseudo", pseudo);
socket.emit("message", message);
return false;
});
Note that I replaced alert with console.log, of which the output can be viewed in the console, which you can open with F12 in Google Chrome. I find it to be less annoying for debugging purposes. (it doesn't create a popup and it can print arrays and objects)

socket.io implementing a simple chat

I tried to ask this on the socket.io google group but no one could (or didn't wanted to) help me.
I have this piece of code on the server side:
var chat = io
.of('/chat')
.on('connection', function (socket) {
socket.emit('message', {
that: 'only'
, '/chat': 'will get'
});
});
chat.on("message", function(data){
console.log(data);
});
While on the client side I have this code:
var chat = io.connect('http://localhost/chat');
chat.on('message', function (data) {
chat.emit('hi!');
});
chat.emit("message", {"this": "is a message"});
On the console I can see that the first message from the server is sent but it seems like the client, once connected and received the message, doesn't emit the 'hi!' message. Moreover I want the client to emit also another message, namely the last line I pasted. Also this message is not received by the server (which in theory should log it).
I'm surely doing something wrong, can anyone point out where exactly this is happening?
What I want to achieve in the end is just setting up a simple chat-like system, but I want this stuff (the channels) working before actually writing the chat itself. Thanks
The reason why that it doesn't the "hi" is not sent is because the first argument in .emit is the event name, in which in here, it is "hi". Technically if you do the following on the server side, I think you should get an undefined data(since you didn't put anything as the second argument which is the object to be sent):
.on('hi',function(data){
console.log(data) // should log "undefined"
});
You can also use .send which is like the web-sockets semantics, and sends to the the message event. If you change the .emit to .send in the client side, it should work.
In summary:
.emit('eventName', 'data') // sends to the eventName name
.send('data') // sends to message event
Working client side code:
var chat = io.connect('http://localhost/chat');
chat.on('message', function (data) {
chat.send('hi!');
});
chat.emit("message", {"this": "is a message"});
I dumbed it down a little bit, but:
Server:
var io = require('socket.io').listen(8080);
var chat = io
.of('/chat')
.on('connection', function (socket) {
socket.send('welcome to the interwebs');
socket.on('message', function(data) {
console.log(data);
});
});
Client:
<html>
<body>
<script src="http://10.120.28.201:8080/socket.io/socket.io.js"></script>
<script type="text/javascript">
var chat = io.connect('http://10.120.28.201:8080/chat');
chat.on('connect', function () {
console.log("connected");
chat.send('hi!');
chat.on('message', function (data) {
console.log(data);
});
});
</script>
</body>
</html>

Faye and nodejs: How to run Faye server side client?

I'm trying to develop a Faye server side client to run automatically as needed. In the official website of Faye, I find only document about server side client, there is no information about how to run it.
Please tell me how to do so
Thanks
There's a key missing piece in the documentation. It appears you need to call client.connect() in order to receive events.
Here is what worked for me:
var faye = require('faye');
var client = new faye.Client('http://localhost:8000/faye');
//This was missing from the documentation
client.connect();
var subscription = client.subscribe('/foo', function(message){
console.log("Event Received");
console.log(message);
})
//This is optional
subscription.then(function() {
console.log('Subscription is now active!');
});
var publication = client.publish('/foo', {text: "Hello World!"});
publication.then(function() {
console.log('Message received by server!');
}, function(error) {
console.log('There was a problem: ' + error.message);
});
just stumpled on this through Google. You should be able to run a client using just this code:
var faye = require('faye'),
client = new faye.Client('http://example.com/faye');
client.subscribe('/some/channel', function(message) {
// process message
});
If you still have trouble, please get on the mailing list at http://groups.google.com/group/faye-users
Create a .rb file and fill with following code
require 'rubygems'
require 'faye'
cliv=Faye::RackAdapter.new(
:mount => '/cliv',
:timeout => 25
)
cliv.listen(3000)
Go to console and type
ruby your_file.rb
Once you have done. create a js with html as following :
<script type="text/javascript" src="http://localhost:3000/faye.js"></script>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js'></script>
<script>
$("document").ready(function(){
faye = new Faye.Client('http://localhost:3000/faye');
faye.connect();
subscribeObj = faye.subscribe("/hi", function(message) {
$("#response").append(message.text);
$("#content").val("");
});
$("#say").click(function(){
content=$("#content").val();
faye.publish("/hi", {text: content});
});
});
</script>
<div id='response'></div>
<br/>
<input type='text' id='content' />
<div style='cursor:pointer;' id='say'> Say Something </div>
And I think u r ready to go. :)

Resources