Socket.io Rooms - javascript

In below program, cashier.js call join_session/room in server, every time it emits cart_items, then the server will emit it to all client in that specific room. So the question is this the right way to do it, do i really need to call join_session/room in my cashier.js every time it emits data?
server.js
let nsp = io.of('namespace_name');
let session;
nsp.on('connection', function (socket) {
socket.on('join_session', function (client_ip) {
session = client_ip;
socket.join(session);
console.log('New session (' + session + ')');
socket.on('cart_items', function (data) {
console.log(session);
console.log(data);
nsp.to(session).emit("cart_items", data);
});
});
});
cashier.js
socket.on('connect', function () {
socket.emit('join_session', session);
socket.emit('cart_items', { name: item.name, price: item.price });
});
customer.js
socket.on('connect', function () {
socket.emit('join_session', session);
socket.on('cart_items', function (data) {
console.log(data);
});
});
FYI when i try to do this in my cashier.js
socket.on('connect', function () {
socket.emit('join_session', session);
});
//on button click
socket.emit('cart_items', { name: item.name, price: item.price });
There were times that client 1 sends data to client 2 and vice versa.

Related

socket connected but not emit the message

Client-Side:
the socket used in website, initially connected and socket id is generated, but when try to emit the message, unable to emit from client to server-side.
<script>
const socket = io("http://localhost:8080");
socket.on("connection",() => {
})
const socketTrigger = () => {
console.log("message")
socket.emit("message", "testing data")
}
</script>
Server Side:
io.on("connection", socket => {
socket.on("message", (data) => {
console.log("message", data)
})
socket.on("startBidding", isAdminPage => {
socket.broadcast.emit("startBiddingArray", isAdminPage);
socket.on("disconnect", () => {
console.log("Client disconnected");
});
});
})
You just assign a variable with an anonymous function, but you don't call it like: socketTrigger(); at the end of the script.

Socket.io: emit from client does not work

I'm trying to emit an event on the client, but the server does not respond at all. A message does not appear in the console ('Received!'), the following event is not initiated. The event must emit when the button is clicked. Other actions, such as outputting a message to the console, work fine, but the event does not start. What is the problem? Сonnection events work properly.
Server:
class ChatHandlers {
constructor() {
this.names = {};
this.connection = this.connection.bind(this);
this.send = this.send.bind(this);
this.message = this.message.bind(this);
}
connection(socket) {
socket.emit('new_user', {
name: 'Example name'
});
}
send(socket) {
console.log('Received!');
var ip = socket.handshake.address;
io.sockets.emit('message', {
name: ip,
message: socket.message
});
}
message(socket) {
console.log('Success!');
}
}
var handlers = new ChatHandlers();
io.on('connection', handlers.connection);
io.on('send', handlers.send);
Client:
var socket = io.connect('http://localhost:8080/');
socket.on('connect', function (data) {
socket.on('new_user', function (data) {
console.log(data.name);
});
socket.on('message', function (data) {
console.log(data);
});
$('#send').click(function() {
socket.emit('send', {
message: $('#mess').val()
});
$('#mess').val('');
});

angular promises and nodejs http get response

I would use the promises of angularJS to fill data to a grid. I'd like to load data "row by row" as soon as the nodeJS's server, on which use the module "mssql" with the "stream" enabled, back to client every single line from the DB.
On the client side I use these functions:
function asyncGreet() {
var deferred = $q.defer();
var _url = 'http://localhost:1212/test';
$http.get(_url).
then(function(result) {
deferred.resolve(result);
}, function(error) {
deferred.reject(error);
}, function(value) {
deferred.notify(value); //<<-- In "value" I would like to get every single row
});
return deferred.promise;
}
$scope.btnTest = function () {
var promise = asyncGreet();
promise.then(function(res) {
console.log('Success: ' + res.data + "\n");
}, function(reason) {
console.log('Failed: ' + reason);
}, function(update) {
console.log('Got notification: ' + update); //<<--
});
};
On nodeJS server those:
app.get('/test', function (req, res) {
//sql for test
var _query = 'select top 50 * from tb_test';
var sql = require('mssql');
var connection;
var config = {
user: 'testUser',
password: '12345',
server: 'localhost\\test',
database: 'testDB',
stream: true
};
connection = new sql.Connection(config, function (err) {
var request = new sql.Request(connection);
request.query(_query);
request.on('recordset', function(columns) {
// Emitted once for each recordset in a query
//res.send(columns);
});
request.on('row', function(row) {
res.write(JSON.stringify(row)); //<<-- I would like intercept this event on client side
// and get the result in my angularJS function on deferred.notify
});
request.on('error', function(err) {
// May be emitted multiple times
console.error(err)
});
request.on('done', function(returnValue) {
// Always emitted as the last one
res.end('DONE');
});
});
});
Anyone can help me with this?
Thanks!
I'm done it using socket.io :)
On angularJS side:
// count the row for test only
$scope.count = 0;
$scope.prova = function () {
mySocket.emit('getTableByRow', {});
mySocket.on('resRow', function (data) {
if (data.event == 'ROW') {
$scope.count += 1;
}else {
$scope.count += " !!DONE!! ";
}
});
};
On NodeJS side:
[ ... connection with DB ... ]
io.on('connection', function (socket) {
socket.on('getTableByRow', function (data) {
_getTableByRow(socket, data);
});
});
_getTableByRow function:
var _getTableByRow = function (socket, data) {
var _query = 'select top 50 * from tb_test';
request.query(_query);
request.on('row', function(row) {
// return only the ids for test
socket.emit('resRow', {event: 'ROW', data: row.id.toString()});
});
request.on('done', function(returnValue) {
socket.emit('resRow', {event: 'DONE'});
});
request.on('recordset', function(columns) {
console.log(columns);
});
request.on('error', function(err) {
socket.emit('resRow', {event: 'ERROR', data: err});
});
}
In this way, as soon as one row is read from the DB, it is immediately sent to the client :)

PeerJS peer not receiving data

I intend to use PeerJs to create P2P connections (data and later video).
I checked the tutorial and used the following code.
In browserA (Chrome 38):
var local;
var remote;
function peerJsInit() {
//listening host
local = new Peer(
{
key: 'myPeerJSKey'
});
local.on('connection', function(conn) {
alert('Connection is open');
conn.on('data', function(data) {
alert('Data: '+data);
});
});
}
function peerSend() {
remote = new Peer(
{
key: 'myPeerJSKey',
debug: true
});
var c = remote.connect('remoteId');
c.on('open', function() {
alert('connected');
c.send(' peer');
});
}
In browserB (Chrome 38):
var local;
var remote;
function peerJsInit() {
//listening host
local = new Peer({
key: 'myPeerJSKey'
});
local.on('connection', function(conn) {
alert('Connection is open');
conn.on('data', function(data) {
alert('Data: '+data);
});
});
}
function peerSend() {
remote = new Peer({
key: 'myPeerJSKey',
debug: true
});
var c = remote.connect('remoteId');
c.on('open', function() {
alert('connected');
c.send(' peer');
});
}
The Connection is open message showed, but the Data and connected messages never.
Can you tell me what I should change?
It seems that I forgot to add another callback.
It is sooo good that JS compiles without a problem, even when callbacks are missing... piece of g*rbage...
So instead of this:
local.on('connection', function(conn) {
alert('Connection is open');
conn.on('data', function(data) {
alert('Data: '+data);
});
});
I have to use this:
local.on('connection', function(conn) {
alert('Connection is open');
conn.on('open',function(){
conn.on('data', function(data) {
alert('Data: '+data);
});
});
});

socket.io error when connecting from iframe

So I have a couple applications on different servers all from inside of our network and I am using node.js and socket.io js to handle real time communication between them which when each is run separately works fine, but when I put application 2 inside an iframe on application 1 I get the following error
"Blocked a frame with origin "http : // 192.128.1.97" from accessing a frame with origin "http : // intranet". Protocols, domains, and ports must match. "
*note I added spaces in the urls above because the page was telling me links weren't allowed.
is there some way to allow the iframe to connect to socket.io? the code is pretty simple, but here is the server code...
/**
* Server js file for node
* this will handle all of the incoming requests from all the apps
* and push them to the clients
*/
var express = require("express"),
app = express(),
http = require("http").createServer(app),
io = require("socket.io").listen(http);
_ = require("underscore");
var participants = [];
// setup the environment and tell node and express what it needs
app.set("ipaddr", "192.168.1.76");
app.set("port", 8080);
app.set("views", __dirname + "/views");
app.set("view engine", "jade");
//further environment setup telling node and express what to use to handle requests
app.use(express.static("public", __dirname));
app.use(express.bodyParser());
//setup the default page
app.get("/", function(request, response) {
//render the view page
//response.render("node_home");
//just post a message to the screen
response.send("Server is up and running");
//respond with a json object
// reponse.json(200, {message: "Server is up and running"});
});
//setup a handler for requests to /message
app.post("/message", function(request, response) {
var message = request.body.message;
if(_.isUndefined(message) || _.isEmpty(message.trin())) {
return response.json(400, {error: "Message is invalid"});
}
var name = request.body.name;
io.sockets.emit("incomingMessage", {message: message, name: name});
response.json(200, {message: "Message received"});
})
io.on("connection", function(socket) {
socket.on("newUser", function(data) {
participants.push({id: data.id, name: data.name});
io.sockets.emit("newConnection", {participants: participants, badgeNumber: data.badgeNumber, id: data.id})
});
socket.on("nameChange", function(data) {
_findWhere(paticipants, {id: socket.id}).name = data.name;
io.sockets.emit("nameChanged", {id: data.id, name: data.name})
});
socket.on("disconnect", function() {
participants = _.without(participants, _.findWhere(participants, {id: socket.id}));
io.sockets.emit("userDisconnected", {id: socket.id, sender: "system"})
});
socket.on("phraseCheck", function(data) {
io.sockets.emit("checkPhrase", {id: data.id, phrase: data.phrase});
});
socket.on('newFluxClient', function(data) {
console.log(data);
io.sockets.emit('fluxConnection', {badgeNumber: data.badgeNumber, id: data.id});
});
socket.on('phraseAllowed', function(data) {
io.sockets.emit('allowedPhrase', {id: data.id, allowed: data.allowed});
});
socket.on('customFunction', function(data) {
console.log(data);
io.sockets.emit('customFunction', data);
});
});
//start the app and have it listen for incoming requests
http.listen(app.get("port"), app.get("ipaddr"), function() {
console.log("Server up and running. Go to http://" + app.get("ipaddr") + ":" + app.get("port"))
});
application 1 code....
/**
* client js file
* this will handle connecting to node and handle the incoming messages
* as well as sending responses and messages to the server
*/
var childSessionId = '',
sessionId = '',
socket = '',
serverBaseUrl = '',
participants = [];
function init() {
serverBaseUrl = 'http://192.168.1.76:8080';
socket = io.connect(serverBaseUrl);
sessionId = '';
function updateParticipants(part) {
participants = part;
$("#participants").html('');
for(var i=0; i<participants.length;i++) {
$("#participants").append('<span id="' + participants[i].id + '">' + participants[i].name + ' ' + (participants[i].id === sessionId ? '(You)' : '') + '<br /></span>');
}
}
socket.on('connect', function() {
sessionId = socket.socket.sessionid;
console.log('Connected ' + sessionId);
socket.emit("newUser", {id: sessionId, name: page.user});
});
socket.on('userDisconnect', function(data) {
$('#' + data.id).remove();
});
socket.on('nameChanged', function(data) {
$('#' + data.id).html(data.name + ' ' + (data.id === sessionId ? '(You)' : '') + '<br />');
});
socket.on('newConnection', function(data) {
if(data.badgeNumber === page.userBadgeNumber) {
childSessionId = data.id;
}
updateParticipants(data.participants);
});
socket.on('fluxConnection', function(data) {
console.log('flux connection data:');
console.log(data);
if(data.badgeNumber === "**********") {
childSessionId = data.id;
}
});
socket.on('incomingMessage', function(data) {
$("#messages").prepend('<b>' + data.name + '</b><br />' + data.message + '<hr />');
});
socket.on('error', function(reason) {
console.log('Unable to connect to server', reason);
});
socket.on('customFunction', function(data) {
console.log(data);
data.data();
});
socket.on('checkPhrase', function(data) {
if(data.id === childSessionId) {
var phrases = shoppingcart.getPhrasesInCart();
var allowed = ($.inArray(data.phrase, phrases) >= 0);
socket.emit('phraseAllowed', {id: data.id, allowed: allowed});
}
});
}
$(document).ready(function() {
init();
})
and application 2 code....
// NODE JS INITIALIZATION
var socket = null;
var sessionId = '';
function initialize_node(){
var serverBaseUrl = 'http://192.168.1.76:8080';
socket = io.connect(serverBaseUrl);
sessionId = '';
socket.on('connect', function() {
sessionId = socket.socket.sessionId;
socket.emit('newFluxClient', {id: sessionId, badgeNumber: "PDX000022", name: "matthew.hicks"});
// socket.emit('newUser', {id: sessionId, badgeNumber: user.badge, name: user.name});
})
socket.on('allowedPhrase', function(data) {
if(sessionId === data.id) {
alert("I'm a preddy little princess. Console logging data returned");
console.log(data);
/*
functions to allow or disallow the phrase
based on data.allowed
it will be true if the phrase is in the shopping cart
and false if it is not
*/
}
});
// $('#phrase').blur(function() {
// checkPhrase();
// })
};
function checkPhrase() {
//var phrase = $('#phrase').val();
var phrase = "Shindigs in Ptown";
socket.emit('phraseCheck', {id: sessionId, phrase: phrase});
}
$(document).ready(function () {
initialize_node();
});
Sorry for the mass amount of code but trying to give all the conte4xt necessary. Essentially server is up and running, application 1 connects and gets a unique session id, then when application 2 tries to connect from the iframe I get the above mentioned error, when application 2 is not in an iframe it connects just fine and gets a session id. Please help if you can, I can't figure out why it is getting blocked and I really need this up and running. Thank you in advance for any help
You have encountered Same Origin Policy.
The simplest solution is to run the iframe from the same server.
Since you have access to I.T time read up on CORS
You will basically have to configure the server to allow XSS from your domain.
You can also try something like:
document.domain = "intranet"
Read up on it here

Categories

Resources