Agent to customer message transformation - javascript

I have two client sides like
1.Agent and customer
2.In Agent .I put a google cdn of socket
3.In customer also.I put a google cdn of socket
4.In Agent Transfers the messages from to nodejs server sends to customer
5.But the customer is out the website .
I write this code in node js server side
app.io.on('connection', function(socket) {
if(arraySockets.length<2){
arraySockets.push(socket);
if(arraySockets.length==1){
SocketAgent = arraySockets[0];
}
if(arraySockets.length==2){
SocketUser = arraySockets[0];
}
}
if(arraySockets.length==2) {
console.log("dffjdsg");
console.log(socket.id);
SocketUser.on('user', function (data) {
console.log(data);
var data = {
message: 'i am from server'
}
});
SocketAgent.on('agent', function (data) {
console.log(data);
var data = {
message: 'i am from server'
}
SocketUser.emit('outputuser',data);
});
}
});
Code on Agent side
services.js file in client Agent side:
schatApp.factory('socket', function ($rootScope) {
var socket = io.connect('http://localhost:8089/');
return {
on: function (eventName, callback) {
socket.on(eventName, function () {
var args = arguments;
$rootScope.$apply(function () {
callback.apply(socket, args);
});
});
},
emit: function (eventName, data, callback) {
socket.emit(eventName, data, function () {
var args = arguments;
$rootScope.$apply(function () {
if (callback) {
callback.apply(socket, args);
}
});
});
}
};
});
controller side code in Agent side
schatApp.controller('homeController', function($scope,socket) {
socket.on('ouputuser',function(data){
alert(data);
});
$scope.Sendingmessage=function(){
var data={message:'hai simhachalam from agent'};
socket.emit('agent',data);
}
});
Client side code in customer side code
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js">
</script>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script>
$(document).ready(function(){
var socket = io.connect('http://localhost:8089/');
$("#sendmessage").click(function(){
var data={message:'iam from user'};
socket.emit('user',data);
});
});
</script>
</head>
<body>
<input type="button" id="sendmessage" value="submit">
</body>
</html>
I am receiving the messages from Agent to nodes server and customer to node server.
when I exchanging the messages socket object is overriding. So how can I solve the problem
socket.on('ouputuser',function(data){
alert(data);
});
data is not getting from the node js server

Related

Websocket is not connecting with javascript

So i'm trying to connect to a websocket server using javascript. I tried doing this with NODEJS with the following code and it worked.
const WebSocket = require('ws');
const ws = new WebSocket('<Websocket Address>', {
origin: '<URL>'
});
ws.on('open', function open() {
ws.send(JSON.stringify({"event":"auth","args":["<My authentication token>"]}))
ws.send(JSON.stringify({"event":"send logs","args":[null]}))
console.log('connected');
});
ws.on('close', function close() {
console.log('disconnected');
});
ws.addEventListener('send logs', function (event) {
console.log('Message from server ', event);
});
ws.on('message', function incoming(data) {
console.log(data);
}, 500);
Is there a way I can write this in plain javascript? Like in script tags? I've read that the following code should work but it's giving me this error Uncaught DOMException: "An invalid or illegal string was specified"
const ws = new WebSocket('<Websocket address>', {
origin: '<URL>'
});
ws.on('open', function open() {
ws.send(JSON.stringify({"event":"auth","args":["<My authentication Token>"]}))
ws.send(JSON.stringify({"event":"send logs","args":[null]}))
console.log('connected');
});
ws.on('close', function close() {
console.log('disconnected');
});
ws.addEventListener('send logs', function (event) {
console.log('Message from server ', event);
});
ws.on('message', function incoming(data) {
console.log(data);
}, 500);
Could anyone tell me what i'm doing wrong?

sender not recieving message sent on socker.io

I am working on a node project using socket.io but when a message is emitted it goes to the sender only and not to other connected clients. please what could I be doing wrong?
this my socket server and client code below.
node - index.js
...
io.on("connection", (socket) => {
//When a new user join
socket.on("joined", (data) => {
socket.emit("welcome", "Welcome to test");
});
//on send
socket.on("send_message", (data) => {
const {name, message} = data;
socket.emit("recieve_message", {name, message});
});
});
...
client - socket.html
...
<body>
<form action="">
<input id="name" autocomplete="off" />
<input id="message" autocomplete="off" /><button>Send</button>
</form>
<ul id="messages"></ul>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.0/socket.io.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<script>
var socket = io.connect('http://localhost:3005');
$('form').submit(function () {
socket.emit('send_message', {name: $('#name').val(), message: $('#message').val()});
$('#message').val('');
return false;
});
socket.emit('joined');
socket.on('welcome', function (msg) {
$('#messages').append($('<li>').text(msg));
});
socket.on('recieve_message', function (msg) {
$('#messages').append($('<li>').text(`${msg.name} - ${msg.message}`));
});
</script>
</body>
...
To send to everyone in the channel use
socket.broadcast.emit()
this will broadcast the message.
Use this cheatsheet for reference next time.
https://socket.io/docs/emit-cheatsheet/

How to disconnect and reconnect socket.io from client?

I have log messages that are being emitted from server to client and that are coming consistently from server and logging to client, Now I have additional functionality to stop and play logs to give some controls to user, So I am thinking on stop to disconnect socket.io connection and on play start socket.io connection again, First i am trying with stop to disconnect connection but i could not emit message to server ,any idea what is wrong with below code or any better solution to achieve these task ?
main.html
<button type="button" class="btn btn-success" ng-click="stopLogs()">stop</button>
ctrl.js
$scope.stopLogs = function(){
socket.emit('end');
}
angularSOcketFactory.js
angular.module('App').factory('socket', function ($rootScope) {
'use strict';
var socket = io.connect('http://localhost:3000');
return {
on: function (eventName, callback) {
socket.on(eventName, function () {
var args = arguments;
$rootScope.$apply(function () {
callback.apply(socket, args);
});
});
},
emit: function (eventName, data, callback) {
socket.emit(eventName, data, function () {
var args = arguments;
$rootScope.$apply(function () {
if (callback) {
callback.apply(socket, args);
}
});
})
}
};
});
server.js
var io = require('socket.io')(server);
io.sockets.on('connection',function(){
// Producer.startProducer();
ditconsumer.start(function(value){
io.emit('ditConsumer',value)
});
io.sockets.on('end', function() {
socket.disconnect();
console.log('it will disconnet connection');
});
});
This code is wrong:
io.sockets.on('end',function () {
console.log('this will disconnet socket connection');
io.sockets.disconnect();
});
You need to apply that event listener to one specific socket and then you need to disconnect one specific socket.
You don't show the general context of your server code, but it could be done like this:
io.on('connection', function(socket) {
socket.on('end', function() {
socket.disconnect();
});
});
You could also just have the client disconnect directly rather than asking the server to do it for you.

Send event to client, from server, and then disconnect the socket (from server)

I want to send an event back to a client, in Socket.io, and immediately after that to disconnect the client. The problem is that calling socket.emit() will not emit anything...
Do you know, or stepped into this kind of problem?
my code is like this:
- on server:
userCredentialsCheck: function (socket, next, callback) {
appLogSys.info('Check cookie!');
.....
var handshake = socket.request;
.....
parseCookie(handshake, null, function (err, data) {
sessionSrv.get(handshake, function (err, session) {
if (err) {
appLogSys.error(err.message);
next(new Error(err.message));
}
else
{
......
socket.emit('na', 'Error checking session! Good bye!');
socket.disconnect();
}
})
})
};
on client:
appSocket.on('na', function(d){
console.log('Error: '+d);
console.log('Now, redirect!');
//REDIRECT!
var delay = 1000; //Your delay in milliseconds
var URL = '/';
setTimeout(function(){ window.location = URL; }, delay);
});
Thank you!

Nodejs stream (Error: Can't set headers after they are sent)

I am trying to build an api from the braintree servers. Referring to this doc https://developers.braintreepayments.com/javascript+node/reference/general/result-handling/search-results
To access all the transactions from their server I have to return a node stream.
ex
app.get('/project', function(req, res) {
if(req.user) {
var stream = gateway.transaction.search(function (search) {
search.customerId().is(req.user.id);
});
stream.on("ready", function () {
console.log(stream.searchResponse);
});
stream.on("data", function (data) {
res.json(data) // can't set headers after they are sent.
});
}
});
I understand a stream returns data in chunks, so the res.json() above is most likely is being called multiple times resulting in Error: Can't set headers after they are sent.
So my question is how can I send that data to the client in one chunk? The nodejs streaming is confusing to me, I am going to read up more about it, but it would be great to understand how to send the data to the client without re-sending the headers.
You shouldn't make any assumptions about data events unless the stream you are reading from is in object mode. You could get one data event or a hundred (depending on the input size of course) because TCP is a stream.
What you probably want is something like this instead (assuming stream is not in object mode):
app.get('/project', function(req, res) {
if(req.user) {
var stream = gateway.transaction.search(function (search) {
search.customerId().is(req.user.id);
});
stream.on("ready", function () {
console.log(stream.searchResponse);
});
var buf = '';
stream.on("data", function (data) {
buf += data;
});
stream.on("end", function() {
res.setHeader('Content-Type', 'application/json');
res.send(buf);
});
}
});
Or just pipe the stream to the response:
app.get('/project', function(req, res) {
if(req.user) {
var stream = gateway.transaction.search(function (search) {
search.customerId().is(req.user.id);
});
stream.on("ready", function () {
console.log(stream.searchResponse);
});
res.setHeader('Content-Type', 'application/json');
stream.pipe(res);
}
});
For an object stream you might do:
app.get('/project', function(req, res) {
if(req.user) {
var stream = gateway.transaction.search(function (search) {
search.customerId().is(req.user.id);
});
stream.on("ready", function () {
console.log(stream.searchResponse);
});
var result = [];
stream.on("data", function (data) {
result.push(data);
});
stream.on("end", function() {
res.json(result);
});
}
});

Categories

Resources