Laravel chat app : Unable to deliver messages to a specific user - node.js

I have been trying to develop a chat app on Laravel with socket.io. Now, I am facing problem that is when a user is sending a message to a specific user, the message is being delivered to all the available users. May I know the section of code you need to help me out? Or there's some other area where I can specifically look into.
const express = require("express");
const app = express();
const server = require('http').createServer(app);
const io = require("socket.io")(server, {
cors: { origin: "*" }
});
server.listen(3000, () => {
console.log('Server is running');
io.on("connection", function(socket) {
console.log("User" + socket.id);
socket.on("messageSent", function(message, senderId) {
socket.broadcast.emit("messageSent", message, this.socket.id)
console.log(this.socket.id);
});
//msg
socket.on("msgSent", function(message) {
socket.broadcast.emit("msgSent", message)
});
socket.on("clientMmsgSent", function(message) {
socket.broadcast.emit("clientMmsgSent", message)
});
});
});
Other code:
<sc ript>
var socket = io("{{config('app.server_url')}}");
function sendMessage(event) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
//console.log('test');
event.preventDefault();
if (event.keyCode === 13) {
var msg = document.getElementById('msg').value;
var client_id = document.getElementById('client_id').value;
var operator_id = document.getElementById('operator_id').value;
//console.log(smg);
$.ajax({
type: "POST",
url: "{{route('send.msg')}}",
data: {
msg: msg,
client_id: client_id,
operator_id: operator_id,
},
beforeSend: function() {
},
success: function(data) {
var msg = `
<div class="operator-msg">
${data.operator_msg}
</div>
`;
console.log(data);
socket.emit("msgSent", {
'data': data,
});
$('#opt_msg').append(msg);
},
error: function(error) {
console.log(error);
}
});
$('#msg').val(" ");
return true;
} else {
return false;
}
}
</sc ript>

Related

Server Sent Event; `EventSource.onmessage` not firing

I'm trying to use the following example of Server Sent Events. Seems like the server is emitting the data, but the event is not firing and no data is recorded in the event stream (through the developer tools).
Angular code (service):
getAlertsEvent(fieldIds: Guid[]): Observable<responseModel.LoanAlert> {
return new Observable(obs => {
fieldIds.forEach(fieldId => {
const source = new EventSource(`http://localhost:3000/loan/alerts/${fieldId}`);
alert('Succesfully creates the EventSource, I see reuslt 200 in Networking tab but with 0 events');
source.onmessage = (ev): void => {
this.zone.run(() => {
alert('This alert will not happen');
obs.next(ev.data);
});
};
source.onerror = (err): void => this.zone.run(() => obs.error(err));
// Also tried this way with no luck:
// source.addEventListener('message', (event) => {
// obs.next(event.data);
// });
});
});
}
Component:
this.loansService.getAlertsEvent(this.fields.map(field => field.fieldId)).subscribe(alert => {
console.log(alert);
});
Node.js code:
const express = require('express');
const parser = require('body-parser');
const app = express();
const EventEmitter = require('events');
const Stream = new EventEmitter();
app.unsubscribe(parser.json());
app.use(
parser.urlencoded({
extended: true,
})
);
app.get('/loan/alerts/:fieldId', function(req, res) {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Access-Control-Allow-Origin': "*",
Conection: 'keep-alive'
});
Stream.on(req.params.fieldId, function(event, data) {
res.write(JSON.stringify(data));
});
});
setInterval(function() {
const item = {
formId: 51415,
alertId: 'asdfasdfasdf',
messageStatus: 'NEW',
messageType: 'ACTION_MESSAGE_FROM_SERVER',
actionType: 'NAVIGATION',
message: 'New Message!',
archiverId: '12345',
documentCode: 3,
from: 'Internal Server Message',
messageTimestamp: new Date().toJSON(),
markedAsRead: false,
};
Stream.emit('aed29580-09fd-e411-b8e1-e61f13cf5d4b', 'message', item);
}, 5000);
app.listen(3000);
console.log('Express E2e Mock server is running');
When manually going to http://localhost:3000/loan/alerts/aed29580-09fd-e411-b8e1-e61f13cf5d4b I'm seeing the messages printed to the screen, so I guess that this is either an Angular or a missing security header.
Thanks!
I just realized, thanks to this answer, that events must be formatted in a specific way. I changed the value of res.write accordingly:
Stream.on(req.params.fieldId, function(event, data) {
res.write('event: ' + String(event) + '\n' + 'data: ' + JSON.stringify(data) + '\n\n');
});

how can i emit data to other client (user) using socket.io?

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.

How to get the responses from websocket server to client(socket.io) using nodejs

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);
});

hapijs with socket.io the right way?

I'm trying to use hapijs with socket.io and already searched a lot about how to integrate socket.io into the hapi server the right way. One approach, I found, is this example and I'm still not sure if this is the way to go. I have to admit that I'm new to hapijs and I'm still learning it :)
var Path = require('path');
var Hapi = require('hapi');
var socketio = require('socket.io');
var server = new Hapi.Server();
server.connection({port: 3000});
server.register(require('vision'), function (err) {
server.views({
engines: {
ejs: require('ejs')
},
relativeTo: __dirname,
path: 'templates'
});
});
var plugins = [
{register: require('./lib/index.js')}
];
server.register(plugins, function (err) {
server.start(function () {
io = socketio.listen(server.listener);
io.on('connection', function (socket) {
socket.on('create', function (room) {
socket.join(room);
console.log("Joined room: " + room);
socket.emit('message', "Joined room");
});
});
console.log('Server running at:', server.info.uri);
});
});
And the lib/index.js
exports.register = function(server, options, next) {
var tasks = [];
server.route([
{
method: 'GET',
path: '/tasks',
handler: function (request, reply) {
reply.view('index', { sid: "6001" });
io.emit('message', "Test");
}
},
{
method: 'POST',
path: '/tasks/{name}',
handler: function (request, reply) {
reply.view('index', { sid: "6001" });
io.emit('message', "Test");
}
},
{
method: 'POST',
path: '/tasks',
handler: function (request, reply) {
io.emit('message', "Test");
}
}
]);
next();
}
exports.register.attributes = {
name: 'routes-tasks',
version: '1.0.0'
};
Please correct me if this is not the way how to use hapijs.
you are near to it.
1)on disconnect close the sockets
socket.disconnect('unauthorized'); or socket.close();
2)use auth for every subscription
{
method: 'POST',
path: '/tasks/{name}',
auth: auth,
handler: function (request, reply) {
reply.view('index', { sid: "6001" });
io.emit('message', "Test");
}
},
3)must important thing is use Access-Control-Allow-Origin otherwise websocket hijacking will happen.
request.response.header('Access-Control-Allow-Origin', 'your domain')
if you need further info let me know.I am happy to help

Node xmpp server don't send messages correctly

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");
});

Resources