I have the following node-xmpp server. At this server I connect 2 clients and send messages one to each other.In console I want to see received message but I see the message that I send.Any ideas?
Here is the code :
server:
'use strict'
var xmpp = require('../index')
, server = null
, Client = require('node-xmpp-client')
var startServer = function(done) {
// Sets up the server.
server = new xmpp.C2S.TCPServer({
port: 5222,
domain: 'localhost'
})
// On connection event. When a client connects.
server.on('connection', function(client) {
// That's the way you add mods to a given server.
// Allows the developer to register the jid against anything they want
client.on('register', function(opts, cb) {
console.log('REGISTER')
cb(true)
})
// Allows the developer to authenticate users against anything they want.
client.on('authenticate', function(opts, cb) {
console.log('server:', opts.username, opts.password, 'AUTHENTICATING')
if (opts.password === 'secret') {
console.log('server:', opts.username, 'AUTH OK')
cb(null, opts)
}
else {
console.log('server:', opts.username, 'AUTH FAIL')
cb(false)
}
})
client.on('online', function() {
console.log('server:', client.jid.local, 'ONLINE')
})
// Stanza handling
client.on('stanza', function(stanza) {
console.log('server:', client.jid.local, 'stanza', stanza.toString())
var from = stanza.attrs.from
stanza.attrs.from = stanza.attrs.to
stanza.attrs.to = from
client.send(stanza)
//console.log('Stanza sent is :'+stanza);
})
// On Disconnect event. When a client disconnects
client.on('disconnect', function() {
console.log('server:', client.jid.local, 'DISCONNECT')
})
})
server.on('listening', done)
}
startServer(function() {
})
Code for clients:
Client1:
var xmpp = require('node-xmpp');
// On Connect event. When a client connects.
client = new xmpp.Client({jid: 'admin#localhost', password: 'secret'});
client.addListener("authenticate", function(opts, cb) {
console.log("AUTH" + opts.jid + " -> " +opts.password);
cb(null, opts);
});
client.addListener('error', function(err) {
console.log(err.toString());
});
client.addListener('online', function() {
console.log("online");
var stanza1 = new xmpp.Element('message', { to: 'admin6#localhost', type: 'chat', 'xml:lang': 'ko' }).c('body').t('aaaaaMessage from admin');
//setInterval(sender,1000);
client.send(stanza1);
});
//client.on("stanza", function(stanza) {
//console.log("STANZA" + stanza);
// console.log('S-a primit ceva: '+stanza);
//});
client.on('stanza',function(message){
console.log('AAAA '+message);
})
client.addListener("disconnect", function(client) {
console.log("DISCONNECT");
});
CLient2 :
var xmpp = require('node-xmpp');
// On Connect event. When a client connects.
client = new xmpp.Client({jid: 'admin6#localhost', password: 'secret'});
client.addListener("authenticate", function(opts, cb) {
console.log("AUTH" + opts.jid + " -> " +opts.password);
cb(null, opts);
});
client.addListener('error', function(err) {
console.log(err.toString());
});
client.addListener('online', function() {
console.log("online");
var stanza = new xmpp.Element('message', { to: 'admin#localhost', type: 'chat', 'xml:lang': 'ko' }).c('body').t('aaaaaMessage from admin6');
//setInterval(sender,1000);
client.send(stanza);
});
client.on("stanza", function(stanza) {
console.log("STANZA" + stanza);
//console.log('S-a primit ceva: '+stanza);
});
//client.addListener('stanza',function(message){
// console.log('AAAA '+message);
//})
client.addListener("disconnect", function(client) {
console.log("DISCONNECT");
});
Related
I am using socket.io in nodejs for chat system, and I am able to send the message on server in socket.js file in nodejs. But when I emit that message to other users from socket in nodejs. Then this message is not receiving on the client side.
Here is my nodejs code:
var users = [];
const io = require('socket.io')(server, {
pingInterval: 5000,
pingTimeout: 5000
});
io.on('connection', (socket) => {
console.log("User connected: ", socket.id);
socket.on("user_connected", function (id) {
users[id] = socket.id;
io.emit("user_connected", id);
});
socket.on('message', (msg) => {
var socketId = users[msg.friendId];
socket.to(socketId).emit('new_message', msg);
let chat = new ChatData({
user: msg.userId,
friend: msg.friendId,
message: msg.message
});
chat.save().then(() => {
console.log('message saved');
}).catch((err) => {
console.log('error is ', err);
});
});
});
Here is my client side code:
const socket = io("ws://localhost:3000");
socket.on('connect', function() {
socket.emit("user_connected", userId);
});
function sendMessage(message) {
let msg = {
userId: userId,
friendId: friendId,
message: message.trim()
}
// Send to server
socket.emit('message', msg);
}
// Recieve messages
socket.on('new_message', (msg) => {
console.log(msg)
});
Client side socket js library https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.1.2/socket.io.js
I have a code that reads unseen emails and creates pdf.
The problem is;
I cannot pull email if any new unseen email exist without executing code again.
var Imap = require('imap');
const MailParser = require('mailparser').MailParser;
var pdf = require('html-pdf');
var fs = require('fs');
var Promise = require("bluebird");
Promise.longStackTraces();
var imapConfig = {
user: '*****',
password: '*****',
host: 'imap.gmail.com',
port: 993,
tls: true
};
var imap = new Imap(imapConfig);
Promise.promisifyAll(imap);
imap.once("ready", execute);
imap.once("error", function(err) {
log.error("Connection error: " + err.stack);
});
imap.connect();
function execute() {
imap.openBox("INBOX", false, function(err, mailBox) {
if (err) {
console.error(err);
return;
}
imap.search(["UNSEEN"], function(err, results) {
if(!results || !results.length){console.log("No unread mails");imap.end();return;}
var f = imap.fetch(results, { bodies: "" });
f.on("message", processMessage);
f.once("error", function(err) {
return Promise.reject(err);
});
f.once("end", function() {
console.log("Done fetching all unseen messages.");
imap.end();
});
});
});
}
const options = { format: 'A2', width:"19in", height:"17in", orientation: "portrait" };
function processMessage(msg, seqno) {
console.log("Processing msg #" + seqno);
// console.log(msg);
var parser = new MailParser();
parser.on("headers", function(headers) {
console.log("Header: " + JSON.stringify(headers));
});
parser.on('data', data => {
if (data.type === 'text') {
console.log(seqno);
console.log(data.html); /* data.html*/
var test = data.html
pdf.create(test, options).toStream(function(err, stream){
stream.pipe(fs.createWriteStream('./foo.pdf'));
});
}
});
msg.on("body", function(stream) {
stream.on("data", function(chunk) {
parser.write(chunk.toString("utf8"));
});
});
msg.once("end", function() {
// console.log("Finished msg #" + seqno);
parser.end();
});
}
Also I have tried to use setInterval to check new unseen emails but I get
'Error: Not authenticated'
How can I pull new unseen emails in a loop and create pdf from that email?
Your observation is correct. You must poll your IMAP (or POP3) server on a regular schedule to keep up with incoming messages. Depending on your requirements, a schedule of once every few minutes is good.
continous polling, or polling every second or so, is very rude. The operator of the IMAP server may block your application if you try to do that: it looks to them like an attempt to overload the server.
I included the socket.io.js in client and also included the custom created socket.js for getting the responses from websocket server to client,when i loading this page in browser automatically stopped the websocket server and in browser console tells WebSocket connection to 'ws://localhost:8000/socket.io/?EIO=3&transport=websocket&sid=2p1ZYDAflHMHiL70AAAA' failed: Connection closed before receiving a handshake response
user defined socket.js code is given below
var socket = io();
var actionItems = []
var beginTakingAction = false
var strOut;
socket.on('transcript', function(x) {
var div = $('div.transcription')
div.html(x);
console.log("transcript " + x);
if (!scrolling) {
div.scrollTop(div[0].scrollHeight);
}
})
socket.on('action', function(x) {
console.log('sending action',x);
actionItems.push(x)
$('div.action').html(actionItems[actionItems.length-1]);
})
socket.on('sentiment', function(x) {
sentimentChart.update(x)
})
socket.on('nlp', function(x) {
wordLengthDistChart.update(x.wordLenghDist);
posTagDistChart.update(x.posTagDist);
})
socket.on('keywords', function(x) {
keywordChart.update(x)
})
socket.on('status', function(status) {
$('div.status').html("status: " + status);
if (status == "connected") {
sentimentChart.reset()
keywordChart.reset()
wordLengthDistChart.reset()
posTagDistChart.reset()
$('div.transcription').html('');
}
})
please give any suggesstions??
my server code is given below
require('dotenv').config()
var WebSocketServer = require('websocket').server;
var http = require('http');
var HttpDispatcher = require('httpdispatcher');
var dispatcher = new HttpDispatcher();
const fs = require('fs');
const winston = require('winston')
winston.level = process.env.LOG_LEVEL || 'info'
var AsrClient = require('./lib/asrClient')
var asrActive = false
var myAsrClient;
var engineStartedMs;
var connections = []
//Create a server
var server = http.createServer(function(req, res) {
handleRequest(req,res);
});
// Loading socket.io
var io = require('socket.io').listen(server);
// When a client connects, we note it in the console
io.sockets.on('connection', function (socket) {
winston.log('info','A client is connected!');
});
var wsServer = new WebSocketServer({
httpServer: server,
autoAcceptConnections: true,
binaryType: 'arraybuffer'
});
//Lets use our dispatcher
function handleRequest(request, response){
try {
//log the request on console
winston.log('info', 'handleRequest',request.url);
//Dispatch
dispatcher.dispatch(request, response);
} catch(err) {
console.log(err);
}
}
dispatcher.setStatic('/public');
dispatcher.setStaticDirname('public');
dispatcher.onGet("/", function(req, res) {
winston.log('info', 'loading index');
winston.log('info', 'port', process.env.PORT)
fs.readFile('./public/index.html', 'utf-8', function(error, content) {
winston.log('debug', 'loading Index');
res.writeHead(200, {"Content-Type": "text/html"});
res.end(content);
});
});
// Serve the ncco
dispatcher.onGet("/ncco", function(req, res) {
fs.readFile('./ncco.json', function(error, data) {
winston.log('debug', 'loading ncco');
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(data, 'utf-8');
});
});
dispatcher.onPost("/terminate", function(req, res) {
winston.log('info', 'terminate called');
wsServer.closeAllConnections();
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end();
});
wsServer.on('connect', function(connection) {
connections.push(connection);
winston.log('info', (new Date()) + ' Connection accepted' + ' - Protocol Version ' + connection.webSocketVersion);
connection.on('message', function(message) {
if (message.type === 'utf8') {
try {
var json = JSON.parse(message.utf8Data);
winston.log('info', "json", json['app']);
if (json['app'] == "audiosocket") {
VBConnect();
winston.log('info', 'connecting to VB');
}
} catch (e) {
winston.log('error', 'message error catch', e)
}
winston.log('info', "utf ",message.utf8Data);
}
else if (message.type === 'binary') {
// Reflect the message back
// connection.sendBytes(message.binaryData);
if (myAsrClient != null && asrActive) {
winston.log('debug', "sendingDate ",message.binaryData);
myAsrClient.sendData(message.binaryData)
}
}
});
connection.on('close', function(reasonCode, description) {
winston.log('info', (new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
wsServer.closeAllConnections();
});
});
wsServer.on('close', function(connection) {
winston.log('info', 'socket closed');
if (asrActive) {
io.sockets.emit('status', "disconnected");
winston.log('info', 'trying to close ASR client');
myAsrClient.close();
myAsrClient = null;
asrActive = false;
}
else {
winston.log('info', 'asr not active, cant close');
}
})
wsServer.on('error', function(error) {
winston.log('error', 'Websocket error', error);
})
var port = process.env.PORT || 8000
server.listen(port, function(){
winston.log('info', "Server listening on :%s", port);
});
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.
I am using node.js with socket.io to push real time notifications to users. However, currently I am just sending back a query result done in my socket.io code and sending it back to the client but I need to let socket know about the changes that occur and to either update with the changes or re-query the db to check for the new number and send that to the client.
For example if a user gets a friend request then the notification count will change and I want socket.io to push the new notification count number to the user.
here is my socket.io code in my app.js file:
io.on('connection', function(socket) {
var sessionID = socket.handshake.sessionID,
session = new connect.middleware.session.Session({ sessionStore: sessionStore }, socket.handshake.session)
console.log('socket: new ' + sessionID)
socket.broadcast.emit('arpNewConn', session.passport.user)
var intervalID = setInterval(function() {
socket.handshake.session.reload(function() {
socket.handshake.session.touch().save()
})
socket.emit('pulse', { heartbeat: new Date().toString(), timestamp: new Date().getTime() })
}, 300 * 1000)
socket.on('disconnect', function() {
console.log('socket: dump ' + sessionID)
socket.broadcast.emit('arpLostConn', session.passport.user)
clearInterval(intervalID)
})
socket.emit('entrance', {message: 'Message works'});
dbnotif.findOne(userID, function (err, user) {
if(err) throw err;
notify = user.notifications;
socket.emit('notify', {notific: notify});
});
});
Here is the client side:
div#CheckSocket
script(src='http://localhost:3000/socket.io/socket.io.js')
script.
$(document).ready(function () {
console.log('socket');
var socket = io.connect('http://localhost:3000/');
console.log('entered1');
socket.on('entrance', function (data) {
console.log('entered');
console.log(data.message);
});
socket.on('notify', function (data) {
console.log('noting');
console.log(data.notific);
if(data.notific !== 0)
$('.notifications').html(data.notific);
});
socket.on('reconnecting', function(data) {
setStatus('reconnecting');
console.log('entered2');
});
function setStatus(msg) {
console.log('connection status: ' + msg);
console.log('entered5');
}
});
Here is the example of adding a friend in the route file:
exports.addContactPost = function(req, res, err) {
async.waterfall([
function(callback) {
var success;
var newFriend = new Friend ({
userId: req.signedCookies.userid,
friend_id: mongoose.Types.ObjectId(req.body.otherUser),
friend_status: 1
});
newFriend.save(function(err){
if(err) {
console.log(err);
} else {
console.log("saved it");
success = true;
}
});
callback(null, success)
},
function(success, callback) {
//if(success === true) {
var success2;
var newFriend2 = new Friend ({
userId: mongoose.Types.ObjectId(req.body.otherUser),
friend_id: req.signedCookies.userid,
friend_status: 2
});
newFriend2.save(function(err){
if(err) {
res.send("request not received");
} else {
success2 = true;
}
});
callback(null, success2);
//} else {
// res.send("error with request sent");
//}
},
function(success2, callback) {
console.log('callback3');
//if(success2 === true) {
var success3;
Notification.findOneAndUpdate({userId: mongoose.Types.ObjectId(req.body.otherUser)}, {
$inc: {notifications: 1}
}, function(err, notify) {
if(err) {
res.send(err);
} else {
console.log(notify);
if(notify.added_notifications === true) {
// enable mail and include general u have got a new request... do not include name because not storing it
}
}
success3 = true;
callback(null, success3);
}],
function(err, results) {
res.json({response: true});
console.log("Add successful");
});
};
Notes: dbnotif is a model being called by mongoose,
userID is a global variable available to the file
I helped him solve this question offline, but we ended up using an EventEmitter as a proxy.
// main.js
var EventEmitter = require('events').EventEmitter;
var emitter = new EventEmitter();
Then add it to each request as middleware:
// elsewhere in main.js
app.use(function(req, res, next) {
req.emitter = emitter;
next();
});
Then in external routes file:
// routes.js
exports.addContactPost = function(req, res, err) {
req.emitter.emit( 'some-key', whatever, data, you, want );
};