I would like to:
retrieve data entered from input forms.
send the data through socket.io and send console log saying done
receive the data on express app.js
insert the data into a mongodb database using mongoose.
I understand emit messages but not sure how to post data through. thank you in advance
my app.js is set up like this:
//app.js config ...
var socket = io.listen(server);
socket.on('connection', function(socket) {
console.log('socket.io connected');
});
app.post('/go', function(req, res) {
socket.on('data', function(data) {
new Order({
routeFrom : data.routeFrom,
routeTo : data.routeTo,
leaving: data.leaving
}).save(function(err, docs) {
if(err) { console.log("error"); }
res.json(data);
});
socket.emit('callback', {done: 'Done'});
});
});
my index.ejs file:
<script src="/socket.io/socket.io.js"></script>
var socket = io.connect('http://localhost:3000');
$('#send').on('click', function() {
$.post('/go', {
socket.emit('data', {
routeFrom: $('#rf').val(),
routeTo: $('#rt').val(),
leaving: $('#l').val()
});
});
socket.on('callback', function(data) {
console.log(data);
});
});
You don't need POST at all.
I would do on the client side:
var socket = io.connect('http://localhost:3000');
$('#send').on('click', function(event) {
event.preventDefault();
socket.emit('data', {
routeFrom: $('#rf').val(),
routeTo: $('#rt').val(),
leaving: $('#l').val()
});
});
socket.on('callback', function(data) {
console.log(data.done);
// Print the data.data somewhere...
});
And on the server side:
//app.js config ...
var socket = io.listen(server);
socket.on('connection', function(socket) {
console.log('socket.io connected');
});
socket.on('data', function(data) {
new Order({
routeFrom : data.routeFrom,
routeTo : data.routeTo,
leaving: data.leaving
}).save(function(err, docs) {
if(err) { return console.log("error"); }
socket.emit('callback', {done: 'Done', data: data});
});
});
Related
I am sending data to all clients but it only APPEND on sender's Message body. In this case, real-time data is only working on sender only but i need to work on every connected users.
After reading the documentation it says, BROADCASTING could be the solution but its not showing for sender(Which means OK) But that also not showing for other connected receivers.
Custom.js
var socket = io.connect("http://localhost:3000/");
$.ajax({
url: 'sent',
type: 'POST',
data: {
msg: 'Some message'
},
dataType: "json",
success: function (data) {
if (data.message) {
socket.emit('send', {
msg: data.msgResult
});
socket.on('msgResult', result => {
$(".msgDiv").append(result);
});
}
}
});
App.js
const app = express();
const http = require("http").Server(app);
const io = require("socket.io")(http);
io.on('connection', (socket) => {
console.log('Socket.io connected...');
socket.on('send', (data) => {
socket.emit('msgResult', data.msg);
});
socket.on('disconnect', () => {
console.log("A socket Discounted ..");
});
});
I want to append data to all connected users including sender too.
If you want to send message to all connected sockets you can use
io.sockets.emit('msgResult', 'data');
and if you want to send message to all connected sockets except sender, use
socket.broadcast.emit('msgResult', 'data');
your index.js for socket server should have
//webServerPort= localhost:3000
const server = http.createServer(app);
let constAppServer = server.listen(webServerPort);
let io = socketServer(constAppServer);
app.set('socket',io);
io.on('connection', function (socket) {
console.log('connection opened');
socket.on('disconnect', function(){
console.log('user disconnected');
});
socket.on('udagent',function(msg){
console.log('message: ' + msg);
});
});
this is your event.js when you want to send a event to frontend
const testFunction =(req,res)=> {
let io = req.app.get('socket');
io.emit('dashboard_event', { "totalMin": data });
}
i had api for broadcasting my admin notifications to all the agents under me by creating and passing this api
const broadCastUpdates =(req,res)=> {
const {message} = req.body
let io = req.app.get('socket');
io.broadcast.emit('broadCastToAgents', { 'data':message });
}
Finally i found my answer. it was a simple mistake which takes a lot of time.
custom.js
var socket = io.connect("http://localhost:3000/");
$.ajax({
url: 'sent',
type: 'POST',
data: {
msg: 'Some message'
},
dataType: "json",
success: function (data) {
if (data.message) {
socket.emit('send', {
msg: data.msgResult
});
}
}
});
socket.on('msgResult', result => {
$(".msgDiv").append(result);
});
App.js
const app = express();
const http = require("http").Server(app);
const io = require("socket.io")(http);
io.on('connection', (socket) => {
console.log('Socket.io connected...');
socket.on('send', (data) => {
socket.emit('msgResult', data.msg);
});
socket.on('disconnect', () => {
console.log("A socket Discounted ..");
});
});
i just plug out my msgResult from ajax submission. That's it.
I'm new in node js and socket io, I'm trying to create interactive quizzes based on pin code given in the url for ex: http://domain/start/5555 should create a quiz page with name 5555 and when clients have the pin code they can connect to this quiz. So it means i have to have a quiz page which shows all connected clients for example but i have some prblems with io.sockets.in(pincode).emit()
because i don't know if i'm creating rooms correctly or not!
here is my code
Client.js
var socket = io();
socket.on('connect', function () {
var params = jQuery.deparam(window.location.search);// To get the name and the room
socket.emit('join', params, function (err) {
if (err) {
alert(err);
window.location.href = '/join.html';
} else {
console.log('No error');
}
});
});
Server.js
app.get('/start/:pincode', (req, res) => {
io.on('connection', (socket) => { // to rigester connection listener
console.log('New user is connected');
// When somebody connects it verifies if the name and the room are valid strings
socket.on('join', (params, callback) => {
if (!isRealSrting(params.name) || !isRealSrting(params.pincode)) {
return callback('Name and pincode are required');
}
socket.join(params.pincode);
users.removeUser(socket.id);//Remove the user from other places
users.addUser(socket.id, params.name, params.pincode);
var x = users.getUserList(params.pincode);
console.log(x);
io.sockets.in(params.pincode).emit('updateUserList', { //here it doesn't work i don't know why!
users: users.getUserList(params.pincode),
pincode: params.pincode
});
socket.emit('newMessage', {
user: params.name,
pincode: params.pincode,
readyMessage: 'You are connected'
});// when the user connect to the server he gets this message
callback();
});
socket.on('disconnect', () => {
var user = users.removeUser(socket.id);
if (user) {
io.emit('updateUserList', users.getUserList(user.pincode));
//io.to(user.room).emit('newMessage', generateMessage('Admin', `${user.name} has left`));
}
});
});
res.render('start.hbs', {
pincode: req.params.pincode
});
});
and the main page
Start.js
var socket = io();
var pincode;
socket.on('updateUserList', function (users) {
console.log('here');
var ol = jQuery('<ol></ol>');
var usercount = users.users.length; // Players number
pincode = users.pincode;
});
Any help or suggestion please?
I want to be able to load these 4 functions: returnAvailable, processMessage, removeUser and joinRoom from an external file, but i get reference errors where it says that socket and nicknames are undefined. How do I modularize my app with respect to dependencies I use?
Here's my code:
server.js
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
// mongoDB init
var mongoose = require('mongoose');
mongoose.connect("mongodb://localhost:27017/chat");
var Message = require('./server/datasets/message');
//include these 4 functions
var util = require('./server/util/util');
//object which contains all users and chatrooms
var nicknames = {
'Music': [],
'Videogames': [],
'Sports': [],
'TV': [],
'Politics': []
};
// middleware
// serves static files
app.use('/client', express.static(__dirname + '/client'));
app.use('/node_modules', express.static(__dirname + '/node_modules'));
// routes
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html')
});
app.get('/api/rooms/get', function(req, res){
res.json(nicknames);
});
server.listen(2000);
// socket functionality
io.sockets.on('connection', function(socket){
socket.on('new user', util.returnAvailable);
// do when 'send message' data is received from client
socket.on('send message', function(data){
util.processMessage(data);
});
// do when 'disconnect' data is received from the client
socket.on('disconnect', function(data){
util.removeUser();
});
socket.on('leave room', function(){
util.removeUser();
});
});
util.js
module.exports.returnAvailable = function (data, callback){
console.log(data);
if(nicknames[data.room].indexOf(data.username) != -1){
callback({ bool: false });
}else {
socket.nickname = data.username;
joinRoom(socket, data.room);
nicknames[data.room].push(socket.nickname);
console.log(nicknames[data.room]);
io.sockets.to(data.room).emit('usernames', nicknames[data.room]);
callback({ bool: true, nickname: socket.nickname});
}
}
module.exports.removeUser = function(){
//console.log(socket.nickname + " disconnected. Bool value: " + socket.nickname==true);
if(socket.nickname==false) return;
// socket.room has to be defined, otherwise crashes if user reloads while not in a roomn
if(socket.room)
{
nicknames[socket.room].splice(nicknames[socket.room].indexOf(socket.nickname), 1);
socket.leave(socket.room);
}
io.sockets.to(socket.room).emit('usernames', nicknames[socket.room]);
}
module.exports.joinRoom = function (data){
socket.join(data);
socket.room = data;
console.log(socket.room);
var query = Message.find({room: socket.room});
query.sort({created:-1}).limit(5).exec(function(err, results){
if(err) { console.log(err); }
else if(results){
io.sockets.to(socket.room).emit('old messages', results);
}
});
}
module.exports.processMessage = function(data){
io.sockets.to(socket.room).emit('new message', {msg : data, nick : socket.nickname});
var message = new Message({
created: new Date,
user: socket.nickname,
message: data,
room: socket.room
});
message.save(function(err){
if(err){
console.log(err);
}else{
console.log('Successfully saved.');
}
});
}
I'm using Express 4.13.4
The socket variable is only available within io.sockets.on('connection', callback function so you can't use it in other files this easily. But you can pass the socket variable to the function where you are trying to use it like this
util.removeUser(socket);
and change the definition of removeUser to accept the socket as an argument
module.exports.removeUser = function(socket){
// your code here
}
The same goes for nicknames variable, use it like this
socket.on('new user', function(data) {
util.returnAvailable(io, socket, nicknames, data);
});
and change the function to accept those arguments
module.exports.returnAvailable = function (io, socket, nicknames, data){
// your code here
}
I'm sending data to all clients but I need to send the data only one client (who make request) too.
app.post(.....){
myModel.save(function (err) {
if (err) return handleError(err);
///send to all
io.sockets.emit("ev", { ...... });
//// send to one client
......
});
}
There is a function called io.sockets.emit but there is no io.socket.emit.
I assume that in the post method you have identified the user or session.
So you can create a room per user to later emit on it.
client.js
var room = "#usernameRoom";
socket.on('connect', function() {
socket.emit('privateroom', room);
});
socket.on('privatemessage', function(data) {
console.log('Incoming private message:', data);
});
server.js
io.sockets.on('connection', function(socket) {
var socket_room;
socket.on('privateroom', function(room) {
socket_room = room;
socket.join(room);
});
socket.on('disconnect', function() {
if (socket_room) {
socket.leave(socket_room);
}
});
});
app.post(.....){
myModel.save(function (err) {
if (err) return handleError(err);
///send to all
io.sockets.emit("ev", { ...... });
//// send to one client
// now, it's easy to send a message to just the clients in a given private room
privateRoom = "#usernameRoom";
io.sockets.in(privateRoom ).emit('privatemessage', 'Never reveal your identity!');
});
}
hope that helps
I have an app like this following:
io.of('/hello').on('connection', function(socket) {
socket.emit('world', {});
});
app.post('/', function *(next) {
console.log("At here......");
var pushMessage = (yield parse.json(this));
console.log(pushMessage);
if(flag !== 0) {
// io.of('/hello/').emit('world', pushMessage);
io.sockets.emit('world', pushMessage);
} else {
console.log("Do Nothing");
}
});
It receive a http request and emit an event. When I use io.sockets.emit it works well but when I specify a namespace with 'io.of('hello').emit' it doesn't work,why?
My client side is this:
var socket = io.connect('http://localhost:3000', {
'reconnection delay': 100,
'reconnection limit': 100,
'max reconnection attempts': 10
});
//server side use io.sockets.emit
socket.on('world', function(data) {
alert(data.a);
});
//if server side use io.of('/hello/').emit
//socket.of('/hello/').on('world', function(data) {
// alert(data.a);
//});
Your code is more or less fine, but you are on different namespaces.
io.sockets.emit() broadcasts to everybody currently connected to your server via socket. That's the reason it works. Technically it's because that's a 'shortcut' for io.of('').emit() ('' being the namespace).
Assuming you're going to use the /hello namespace, this is what you have to do on your client:
var socket = io.connect('http://localhost:3000/hello'); // your namespace is /hello
on the server you first have to listen for connections on that namespace:
io.of('/hello').on('connection', function(socket) {
socket.emit('world', { a: 'hi world' });
});
then:
io.of('/hello').emit('something');
You may want to look at these: socket.io: How to use and socket.io rooms on GitHub
### UPDATE ###
I conducted a little test:
client:
$('document').ready(function() {
var socket = io.connect("localhost:3000/hello");
socket.on('hello', function() {
console.log('hello received');
});
var data = {};
data.title = "title";
data.message = "message";
setTimeout(function() {
$.ajax({
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json',
url: 'http://localhost:3000/hello',
success: function(data) {
console.log('success');
console.log(JSON.stringify(data));
}
});
}, 2000);
});
server:
io.of('/hello').on('connection', function() {
console.log("client connected");
});
app.post('/hello', function(req, res) {
io.of('/hello').emit('hello');
});
... and it worked. I copied the jquery-ajax code from here.