io.sockets.in(room).emit() not working - javascript

For some reason when I want to emit to sockets in a given room I get nothing. It does work when I emit just to one specific socket, however. Here is my code:
//client side
var socket = io();
var room = "abc";
startButton.onclick = function(){
socket.emit('startGame',{room:room});
}
socket.on('startGameResponse', function(msg){
console.log(msg);
});
//server side
var serv = require('http').Server(app);
var io = require('socket.io')(serv,{});
io.sockets.on('connection', function(socket){
socket.on('startGame',function(data){
var room = data.room;
socket.join(room);
io.sockets.in(room).emit('startGameResponse','player joined');
}

Related

Socket.io is not emitting value

I am having problem in receiving values emitted by socket.io, I am not getting where is the problem. Here am posting the code please help me to solve the problem.
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var bodyParser = require('body-parser');
var path = require('path');
var fs = require('fs');
var spawnSync = require('child_process').spawnSync;
....
app.post('/loadImage',upload.any(),function(req, res) {
fs.readFile('/home/pathtofile/file.json','utf8',function(err,data){
if(err){
console.log(err);
}else{
//console.log(data);
var precjson = JSON.parse(data);
var loaded_filename = precjson.Filename;
io.emit('emitfilename',{loaded_filename});
}
})
}
http.listen(8080,'0.0.0.0',function(){
console.log('listening on 8080');
})
And here is my code where I am receiving the emitted values:
<script type="text/javascript">
var socket = io.connect('http://localhost:8080');
socket.on('emitfilename',function(data){
//console.log(data);
var li = document.createElement('li');
var filename = document.createElement('h4');
filename.textContent = 'File Name:' + data.filename;
li.appendChild(filename);
document.getElementById('filenameoutput').appendChild(li);
});
</script>
Instead of getting file name , I am getting undefined. Can any one please help me.
You can't use "io" variable to emit data. You can use current socket of the client that just connected to send data :
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
Or use io.sockets to emit to all sockets
io.sockets.emit('users_count', clients);
Hope it solve your problem ! Thanks !

client code in node js

I am new to Nodejs and am trying to set up a server client connection using sockets. Below is my code. Server is working OK but client is not connecting.
Please can anyone help me figure out the mistake.
Much Thanks
jessi
Server.js
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
io.on('connection', function(socket){
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
io.on('data', function(data) {
console.log('DATA from client is: ' + data);
// Close the client socket completely
});
server.listen(4200);
console.log('Monitoring server listening on port 4200');
Client.js
var HOST = '127.0.0.1';
var PORT = 4200;
var express = require('express');
var app = express();
var client = require('http').createServer(app);
var io = require('socket.io')(client);
client.connect(PORT, HOST, function()
{
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
// Write a message to the socket as soon as the client is connected,
// the server will receive it as message from the client
io.write('I am Chuck Norris!');
});
// Add a 'data' event handler for the client socket
// data is what the server sent to this socket
client.on('data', function(data) {
console.log('DATA: ' + data);
// Close the client socket completely
client.destroy();
});
// Add a 'close' event handler for the client socket
client.on('close', function() {
console.log('Connection closed');
});
For the client you use the socket.io-client package instead. The client side doesn't require the use of the Express portion since you're not recreating a web server on the client. If you look at your current code you're essentially recreating the Socket server which isn't what you want to do.
All that is necessary is to create a new Socket.io client and register your various event handlers.
var socket = require('socket.io-client')('localhost:4200');
socket.on('data', function(data) {
// handle incoming data
console.log(data);
});

Server to server Socket IO messaging

Context:
Node.js running a server with require("socket.io");
Node.js running another server with require("socket.io-client");
Receiving acknowledgements (from the other server) when using the standard :
io.on("connection", function() { console.log("Something connected."); });
Problem:
Unfortunately, I cannot get the CLIENT on either server both are running client & server socket.io to emit a message to the server of the other.
I realize it's probably a code error, so I'll include that for correctness' sake, but for the record I'm wondering if there's something I'm doing wrong semantically as opposed to code-wise.
Code: (LoginServer.js)
var app = require('http').createServer();
var io = require('socket.io')(app);
var ioc = require("socket.io-client");
var LoginServer = (function() {
function LoginServer() {
this.gameServerSocket = ioc.connect("http://localhost:3031", {reconnect: true});
}
LoginServer.prototype.initialize = function() {
var self = this;
io.listen(3032);
io.on("connection", function(socket) {
socket.emit("connection");
});
this.gameServerSocket.on("connection", function() {
console.log("Game Server Connected!");
self.gameServerSocket.emit("login", {accountName: "default"});
});
}
return LoginServer;
})();
exports.LoginServer = LoginServer;
Code: (GameServer.js)
var app = require('http').createServer();
var io = require('socket.io')(app);
var ioc = require("socket.io-client");
var GameServer = (function() {
function GameServer() {
this.loginServerSocket = ioc.connect("http://localhost:3032", {reconnect: true});
this.loginServerSocket.emit("connection");
}
GameServer.prototype.initialize = function() {
var self = this;
io.listen(3031);
io.on("connection", function(socket) {
socket.emit("connection");
});
this.LoginServerResponses();
}
GameServer.prototype.LoginServerResponses = function() {
var self = this;
this.loginServerSocket.on("connection", function() {
console.log("Login Server Connected!");
});
this.loginServerSocket.on("login", function(data) {
console.log("Login Server:", data);
});
}
return GameServer;
})();
exports.GameServer = GameServer;
After doing some more testing, I realized your code is working fine. Maybe you're calling your modules incorrectly? I used this as my index.js and the two server-client pairs connected fine:
// index.js
var GameServer = require('./GameServer.js').GameServer;
var LoginServer = require('./LoginServer.js').LoginServer;
var lserver = new LoginServer();
var gserver = new GameServer();
lserver.initialize();
gserver.initialize();
Side note on sockets
I believe you can accomplish what you want to do with only 1 stream between the login and game servers. Here a redo of your code using only 1 server and 1 client that does the same thing:
GameServer.js:
var http = require('http');
var io = require('socket.io');
function GameServer() { }
GameServer.prototype.initialize = function() {
var self = this;
self.httpServer = http.createServer();
self.ioServer = io(self.httpServer);
self.ioServer.listen(3031);
self.ioServer.on("connection", function(socket) {
socket.emit("connection");
});
this.LoginServerResponses();
}
GameServer.prototype.LoginServerResponses = function() {
var self = this;
this.ioServer.on("connection", function() {
console.log("Login Server Connected!");
});
this.ioServer.on("login", function(data) {
console.log("Login Server:", data);
});
}
exports.GameServer = GameServer;
LoginServer.js:
var ioc = require("socket.io-client");
function LoginServer() {
this.gameServerSocket = ioc.connect("http://localhost:3031", {reconnect: true});
}
LoginServer.prototype.initialize = function() {
var self = this;
self.gameServerSocket.on("connection", function() {
self.gameServerSocket.emit("connection");
});
this.gameServerSocket.on("connection", function() {
console.log("Game Server Connected!");
self.gameServerSocket.emit("login", {accountName: "default"});
});
}
return LoginServer;
exports.LoginServer = LoginServer;
"Unfortunately, I cannot get the CLIENT on either server both are running client & server socket.io to emit a message to the server of the other."
What you really want to do is 1 server, and allow clients to connect.
The server can communicate to the clients, so does the clients to the server, back and forth.
server.js
var app = require('http').createServer();
var io = require('socket.io')(app);
io.listen(3032);
io.on('connection', function(socket) {
console.log('A user(a client) connected!');
// lets welcome this particular client with a nice msg :)
socket.emit('msg group', 'Welcome client! you can emit msgs for me to tell every client in "to everyone please"');
// lets tell everyone someone joined
io.emit('msg group', 'guys someone special joined :)!');
socket.on('to everyone please', function(freedomMsg) {
io.emit('msg group', "a client told me (the server) to send this to everyone (every clients)!: " + freedomMsg);
});
});
aClient.js
var ioc = require("socket.io-client");
var socket = ioc("http://localhost:3032");
// general chat
socket.on('msg group', function(msg) {
console.log(msg);
});
function msgEveryone(message) {
socket.emit('to everyone please', message);
}
msgEveryone('whats up guys?');
I hope that with this you'll understand a bit more on how socket.io (or sockets in general) works :)
Code: (GameServer.js)
first delete these code :
this.loginServerSocket.on("login", function(data) {
console.log("Login Server:", data);
});
second change code:
GameServer.prototype.initialize = function() {
var self = this;
io.listen(3031);
io.on("connection", function(socket) {
socket.emit("connection");
});
this.LoginServerResponses();
}
to
GameServer.prototype.initialize = function () {
var self = this;
io.listen(3031);
io.on("connection", function (socket) {
socket.emit("connection");
socket.on("login", function (data) {
console.log("Login Server:", data);
});
});
this.LoginServerResponses();
}
Try this:
LoginServer.js
var app = require('http').createServer();
var io = require('socket.io')(app);
var ioc = require("socket.io-client");
var LoginServer = (function() {
function LoginServer() {
this.gameServerSocket = ioc.connect("http://localhost:3031", {reconnect: true});
}
LoginServer.prototype.initialize = function() {
var self = this;
io.listen(3032);
io.on("connection", function(socket) {
// a client, maybe game server, is connected
socket.on("login", function(data){ console.log("Credentials: "+ data); });
});
this.gameServerSocket.on("connect", function() {
console.log("Connected to Game Server!");
// Send event to game server
});
}
return LoginServer;
})();
exports.LoginServer = LoginServer;
GameServer.js
var app = require('http').createServer();
var io = require('socket.io')(app);
var ioc = require("socket.io-client");
var GameServer = (function() {
function GameServer() {
this.loginServerSocket = ioc.connect("http://localhost:3032", {reconnect: true});
}
GameServer.prototype.initialize = function() {
var self = this;
io.listen(3031);
io.on("connection", function(socket) {
// a client, maybe login server, is connected
});
this.LoginServerResponses();
}
GameServer.prototype.LoginServerResponses = function() {
var self = this;
this.loginServerSocket.on("connect", function() {
console.log("Connected to Login Server !");
// Try to login
self.loginServerSocket.emit("login", {accountName: "default"});
});
}
return GameServer;
})();
exports.GameServer = GameServer;

How can I have faye-websockets code running in the browser?

I'm new with node.js/express and all and I want to be able to notify any clients in browser about a new message received from some algorithm in the back-end. The publisher algorithm connect to the websocket and writes the message.
As far as I've looked there were examples which recommended websockets but I haven't been able to run that code in browser only in console.
Example client code:
var WebSocket = require('faye-websocket');
var ws = new WebSocket.Client('ws://localhost:1234');
var http = require('http');
var port = process.env.PORT || 1235;
var server = http.createServer()
.listen(port);
// receive a message from the server
ws.on('message', function(event) {
alert(JSON.parse(event.data));
});
Thank you
Found the answer after some trial/error iterations.
The algorithm now does a POST to an URL which in turn triggers a write to sockets for all connected clients via socket.io.
Client code:
var socket = io('http://localhost:7777');
socket.on('message', function (msg) {
document.body.insertAdjacentHTML( 'beforeend', '<div id="myID">'+msg+'</div>' );
});
And on the server, when client connects I retain it's socket into an array so I can write to each one:
Server code:
io.on('connection', function(socket){
console.log('a user connected: '+socket.id);
var id = clientCount++;
clientSockets[id] = socket;
socket.on('disconnect', function(){
console.log('user disconnected');
delete clientSockets[id];
socket = null
});
});
app.post('/alerts', function(req, res) {
req.accepts(['json', 'application']);
console.log("Algo did a POST on /alerts!");
// send the message to all clients
//console.log(req.body);
for(var i in clientSockets) {
clientSockets[i].send(JSON.stringify(req.body));
}
res.send(200);
});
In conclusion, I'm not using faye-websockets but instead socket.io

Javascript create object with data structure like this

I would like to create an object with a similar data structure if possible.
Must I create a new object for every player? Could somebody tell me how?
players
players.name='John'
players.John.age='12'
players.John.adress='London ..'
players.John.telnumber='09876587655'
edit1
Sorry I know this is the basic. I just ask one more question an them i will try learn better javascript. I need to pass data stored in "event" to object."event".id (to be like players.John.id instead players.event.id)
Sorry for my bad english.
// in app.js
var fs = require('fs');
var socketio = require('socket.io');
Tail = require('tail').Tail;
var express = require('express');
var http = require('http');
var colors = require('colors');
var app = express()
, server = require('http').createServer(app)
, io = socketio.listen(server); // socket needs to listen on http server
server.listen(9099);
app.use(express.static(__dirname + '/public'));
var port = process.env.PORT || 3000;
app.listen(port, function() {
console.log('\r\n');
console.log("Express listening on port " + port +'.'.green);
});
// Routing
//app.use(express.static(__dirname));
// usernames which are currently connected to the chat
//var players = [];
var players = {};
io.sockets.on('connection', function(socket) {
// do all of your socket work in here
console.log('\r\n');
console.log("Connection".green);
var sessionid = socket.id;
console.log(sessionid);
// Success! Now listen to messages to be received
socket.on('message',function(event){
console.log('Received message:',event);
});
socket.on('add user',function(event){
console.log('New User:',event);
// we store the username in the socket session for this client
socket.username = event;
// add the client's username to the global list
players.event = {};
players.event.id = sessionid;
//players.John.foo = "yeah"
//players.John.name = "John"
console.log(players);
socket.emit('login', {});
// echo globally (all clients) that a person has connected
socket.broadcast.emit('user joined', {
username: socket.username
});
});
//socket.emit('start', 'newround');
});
edit2
Got it working.
// in app.js
var fs = require('fs');
var socketio = require('socket.io');
Tail = require('tail').Tail;
var express = require('express');
var http = require('http');
var colors = require('colors');
var app = express()
, server = require('http').createServer(app)
, io = socketio.listen(server); // socket needs to listen on http server
server.listen(9099);
app.use(express.static(__dirname + '/public'));
var port = process.env.PORT || 3000;
app.listen(port, function() {
console.log('\r\n');
console.log("Express listening on port " + port +'.'.green);
});
// Routing
//app.use(express.static(__dirname));
// usernames which are currently connected to the chat
//var players = [];
var players = {};
io.sockets.on('connection', function(socket) {
// do all of your socket work in here
console.log('\r\n');
console.log("Connection".green);
var sessionid = socket.id;
console.log(sessionid);
// Success! Now listen to messages to be received
socket.on('message',function(event){
console.log('Received message:',event);
});
socket.on('add user',function(event){
console.log('New User:',event);
// we store the username in the socket session for this client
socket.username = event;
// add the client's username to the global list
players[event] = {};
players[event].id = sessionid;
//players.John.foo = "yeah"
//players.John.name = "John"
console.log(players);
socket.emit('login', {});
// echo globally (all clients) that a person has connected
socket.broadcast.emit('user joined', {
username: socket.username
});
});
//socket.emit('start', 'newround');
});
You're looking for a players object, with individual players referenced by name. So:
var players = {};
players['John'] = {
'age' = 12,
'address' = 'London...',
'telnumber' = '09876587655'
};
You can also access "John" as players.John, but that gets tricky if any of the names contain spaces, etc.
Similarly, the player attributes can be accessed either via:
players.John['age'] = 13;
or
players.John.age = 13;
var name = "John";
var players = {};
players[name] = {};
players[name].age = '12';
players[name].address = "address";
players[name].telnumber = "tel";

Categories

Resources