socket.io emit/broadcast to every client - javascript

I can not find out how to emit from the client or an other NodeJS file to every client.
Emitting to the server worked, but not to every other client.
Servercode:
var io = require('socket.io').listen(app.listen(8080));
io.on('connection', function (socket) {
socket.on('playerData', function(data) {
console.log(data);
});
});
Clientcode:
<script src="https://cdn.socket.io/socket.io-1.3.5.js"></script>
<script>
var socket = io('http://localhost:8080');
socket.on('playerData', function(data) {
console.log(data);
});
</script>
I am using Node.JS - Jade, Express, Socket.io (and AngularJS, but not in this part of the code)
The Serverside console.log is being called when I call my emit function, but on the Clientside nothing happens.
Currently using Chrome as my browser.

You need to emit from the client to the server and then broadcast that message from the server to each client.

Related

Why does my socket.io app disconnect immediately when run on Raspberry pi?

I am attempting to build a node.js application on a Raspberry Pi which can communicate with a remote socket.io server.
The socket.io server quite simply writes to the console when a new connection is established and when an existing connection is closed.
The socket.io client works as expected when run in a browser.
However, when I run the client code from a Raspberry Pi it connects and immediately terminates. This does not allow me to perform any function such as emitting or receiving.
The on connect event is never fired.
var io = require('/usr/local/lib/node_modules/socket.io-client');
var serverUrl = 'http://remoteserver.com';
console.log('Connecting to ' + serverUrl);
var socket = io.connect(serverUrl);
socket.on('connect', function(socket) {
console.log('Connection established!');
console.log(socket.id);
socket.on('disconnect', function() {
console.log('Disconnected from server');
});
});
The code above will output:
Connecting to: http://remoteserver.com
On the server side, the output will show a new connection and eventually a timeout close.
Why is the client on connect event not firing? How can I persist this connection so that I can eventually send inputs to the server?
Remove the line:
socket.close();
from your code. You are closing the socket immediately. Remember that all the event handlers are asynchronous. They are non-blocking and will be called some time in the future. Meanwhile, the rest of your code runs to completion and thus your socket.close() is executed before your client has any chance to get any events (other than the disconnect event).
If you want to do some stuff and then close the socket, then you need to close the socket only from some event handler that indicates that your operation is complete and you are now done with the socket.
You only need to call socket.close() when you want to close the connection from the raspberry pi. Also, the socket.io-client documentation does not use the .connect method, but instead calls require('socket.io-client')(serverUrl)
var io = require('/usr/local/lib/node_modules/socket.io-client');
var serverUrl = 'http://remoteserver.com';
console.log('Connecting to ' + serverUrl);
var socket = io(serverUrl);
socket.on('connect', function(socket) {
console.log('Connection established!');
console.log(socket.id);
});
socket.on('disconnect', function() {
console.log('Disconnected from server');
});
//Removed the socket.close() line

socket.io not reconnecting after a disconnect

I am developing a node.js application using socket.io to communicate between server and client. If the server faces any error, I send an error message to the client and I close the connection from both server and client. However when the client tries to reconnect, it is no longer able to connect to the server. My code
server.js
io.sockets.on('connection', function(socket) {
/*Some code*/
stream.on('error',function(errormsg){
socket.emit('error',{txt: "Error!"});
socket.disconnect();
});
});
client.js
var server_name = "http://127.0.0.1:5000/";
var socket = io.connect(server_name);
socket.on('error',function(data){
console.log(data.txt);
socket.disconnect();
});
function submitclick()
{
var text="hello";
if(socket.connected ==false)
socket= io.connect({'forceNew': true});
console.log(socket.connected);
}
Status of socket.connected is false. I do not receive it on the server side either.
I don't think your call to io.conncet is synchronous, you're checking socket.connected too early. If you want to verify that your reconnect succeeds, try it like this:
function submitclick()
{
var text="hello";
if(socket.connected ==false) {
socket= io.connect({'forceNew': true});
socket.on('connect', function() {
console.log('Connected!');
});
}
}
Edit:
As #jfriend00 points out there's probably no need for you to do the socket.disconnect() in the first place as socket.io should automatically be handling reconnection.

Why don't I see a response from socket.io-client with node.js?

var io = require('socket.io-client'),
socket = io.connect('targeturl', {
port: 8080
});
socket.on('connect', function () {
console.log("socket connected"); //this is printed.
});
socket.emit('list', {"user":'username',"token": 'mytoken'});
socket.on('message', function(data){
console.log(data);
});
socket.on('error', function(data){
console.log(data); //nothing is printed
});
I see the message 'socket connected' when running this from node.js on the command line but I don't see a response from the 'list' call.
Note that this is a specific question about using socket-io-client from Node.js as a command line application.
I have verified using curl that I can reach the socket server which is REMOTE i.e I do not have the server code but I know that it uses socket.io.
I'm no expert on the matter, but it appears you're attempting to emit the message before the connection is established. (This stuff is asynchronous after all.)
Try moving the emit call inside of the handler for the 'connect' event, to ensure that it happens afterward.

socket.io not working on several clients

I'm trying to build a simple chat client and am having some issues getting it working across multiple clients. Chances are I've missed something really simple. When I send something from one client it is logged in that client but not in any others.
Server:
var io = require('socket.io').listen(5000);
io.sockets.on('connection', function (socket) {
socket.on('send', function (data) {
socket.emit('receive', data);
});
});
Client:
var socket = io.connect('http://localhost:5000');
socket.on('receive', function(data){
console.log("Data received at " + new Date() + ": " + data);
});
The socket variable that gets passed to your callback function is a handle on the client that connected, so socket.emit is behaving correctly, i.e. it should only send to the client that originated it.
Try:
socket.broadcast.emit('receive', data);
to send to everybody except the originating client, or
io.sockets.emit('receive', data);
to send to all clients including the originator.
You want to emit on all sockets, not just the one that sent the message.
So you should be using:
io.sockets.emit('recieve', data);
This is assuming that you aren't logging the data on the sending client before sending it to the server. In that case you'll want to use:
socket.broadcast.emit('recieve', data);
Which will send the message to all connected clients except the sender.
See here for reference on Socket.io
Edit: Trevor beat me to it. However, for some additional clarification: io.sockets is the same as io.of(''). Which is handy to know for when you start using namespaces in a scoket.io app.

Is it possible to update a single part of a page using Nodejs and Socket.io?

I'm trying to create a basic Node application, every time a client connects I want to update the counter which is displayed on the page. (My goal is to create this application in its most simple, and learnable form to demonstrate node to my lecturer).
Server side application snippets:
Making the connection
var clients = 0;
io.sockets.on('connection', function (socket) {
socket.on('connect', function () { clients += 1 });
socket.on('disconnect', function(){ clients -= 1 });
});
Rendering the page
app.get(navigation.chat.page, function(req, res){
res.render('chat', {
title: navigation.chat.title,
connected: clients
});
});
Chat page jade template snippet:
span#client_count #{connected}
| connected clients
Client side jQuery, Socket.io and JavaScript
var socket = io.connect('http://localhost');
$(document).ready(function(){
socket.on('connect', socket.emit('connect'));
});
Problem:
The number of connected clients only updates upon page refresh. I would like the number to be updated asynchronously. I'm quite new to node, socket.io and express so i'm unsure how to tackle the problem!
rather than incrementing on client side, better keep counter value on server side, increment on connection and decrement on disconnect io events. Then, you can send updated counter (in the same event handlers where value was changed). On client side, listen for event with counter and when received, replace value in html.
server :
var users_count = 0;
io.sockets.on('connection', function (socket) {
//on connection, update users count
++users_count;
//send it to every opened socket
io.sockets.emit('users_count', users_count);
//when this socket is closed
socket.on('disconnect', function () {
//user disconnected
--users_count;
//emit to every opened socket, so everyone has up to date data
io.sockets.emit('users_count', users_count);
});
});
client :
jQuery(function($){
//connect to localhost
var socket = io.connect('http://localhost');
//handle users_count event, by updating our html
socket.on('users_count', function(data){
$('#client_count').text(data);
});
});

Categories

Resources