I have implemented a basic comunication through websockets using Socket.IO. The problem is when the client refresh the browser and then initialize again the websocket this start to get duplicate messages. Also is incrementing by one each time that the browser is refreshed.
I take a look to the Socket object on the server and alwas says that there is only one client connected. It seems that the emit event or on.connection event is triggering multiple times.
Here is the code on the server:
run.js
const http = require('http')
const serverSocket= require('./server')
const corsify = require('corsify')
const socketio = require('socket.io')
const cors = corsify({
'Access-Control-Allow-Origin': 'http://localhost:8000',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE',
'Access-Control-Allow-Headers': 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept, Authorization'
})
const handler = cors((req, res) => {
if (req.url === '/') {
// TODO: status message
res.end('Service working properly!')
} else {
res.statusCode = 404
res.end()
}
})
const app = http.createServer(handler)
const io = socketio(app)
serverSocket(io)
app.listen(3455, () => console.log('listening 3455'))
server.js
module.exports = function (io) {
io.on('connection', socket => {
var handshakeData = socket.request;
ns = handshakeData._query['ns']
// create new namespace (or use previously created)
var nsp = io.of(ns);
nsp.on('connection', function (socket) {
socket.emit('message', 'hello!')
});
})
return io
}
client.js
socket_uri and namespace are provided by myself, just ignore them.
var io = require('socket.io-client')
module.exports = {
socket: null,
init: function(){
this.socket= io(socket_uri + '/' + namespace, { query: 'ns='+ namespace});
this.socket.on('connect', this.onOpen.bind(this));
this.socket.on('disconnect', this.onClose.bind(this));
this.socket.on('error', this.onError.bind(this));
this.socket.on('message', this.onMessage.bind(this));
},
onOpen: function(event) {
console.log(event)
},
onClose: function(event) {
console.log(event)
},
onError: function(event) {
console.log(event)
},
onMessage: function(payload) {
// onMessage is triggering one more time per each refresf.
// Starting in one like normal, but then after refresh is
// showing up 2, 3, 4, 5... times
console.log(payload)
},
};
Any help will be really apreciate.
Thanks.
Related
I have socket.io v2.3 and I'm trying to get all connected sockets from a different file. Here's my setup:
const io = require('socket.io');
let IO;
let myNameIO;
module.exports = {
create: (server) => {
IO = io(server, { cors: { origin: '*' } });
const redisConnection = redisAdapter({ host: redisHost, port: redisPort });
IO.adapter(redisConnection);
IO.on('connection', (socket) => {
console.log('a user connected');
});
IO.on('disconnect', (socket) => {
console.log('disconnected');
});
myNameIO = IO.of('/my-name');
myNameIO.on('connection', function (socket) {
console.log('someone connected');
});
},
getIO: () => IO,
getMyNameIO: () => myNameIO,
};
IN a diff file I import getMyNameIO and I'm trying to get all connected clients but I'm having trouble with that. Tried doing
getMyNameIO().clients((error, clients) => {
console.log(clients, '-=--=-=');
});
But clients isn't a function. I then tried importing the socket.io and use.of, but that doesn't return anything. What am doing wrong and how can I fix it?
Give this a try. I suspect either a scope issue or order of operations issue. Either way this should resolve it or give you a more useful error. I've tried to maintain your naming scheme which gave me a small headache. =)
const io = require('socket.io');
const socketServer = {
_initialized: false,
_myNameIO: null,
_IO: null,
_myNameIOClients: new Map(),
get myNameIO() {
if (!socketServer._initialized) throw new Error('socketServer.create not called!')
return socketServer._myNameIO
},
get IO() {
if (!socketServer._initialized) throw new Error('socketServer.create not called!')
return socketServer._IO
},
create: (server) => {
IO = io(server, { cors: { origin: '*' } });
const redisConnection = redisAdapter({ host: redisHost, port: redisPort });
IO.adapter(redisConnection);
IO.on('connection', (socket) => {
console.log('a user connected');
});
IO.on('disconnect', (socket) => {
console.log('disconnected');
});
myNameIO = IO.of('/my-name');
myNameIO.on('connection', function (socket) {
console.log('someone connected');
socketServer._myNameIOClients.set(socket.id, socket)
});
},
//getIO: () => IO,
//getMyNameIO: () => myNameIO,
getIO: () => socketServer._IO,
getMyNameIO: () => socketServer._myNameIO,
get myNameIOClients() {
return socketServer._myNameIOClients
},
getClients: () => new Promise((resolve,reject)=>socketServer._myNameIO.clients((error, clients)=> error ? reject(error) : resolve(clients))
}),
};
module.exports = socketServer
when I do console.log(socketServer.myNameIO.sockets); I get an object with all the sockets. how can I get an array?
Looking at the API https://socket.io/docs/v2/server-api/#Namespace I don't see a reference to Namespace.sockets. That doesn't mean it doesn't exist. I added a getClients function that will return an array of client IDs.
const socketServer = require('./socketServer ')
socketServer.getClients()
.then(clients=>{
// clients an array of client IDs
})
.catch(e=>console.error('Error is socketServer.getClients()', e))
I think what you really want is to manage the connections. One way to do it is by mapping the connections as they come in.
const socketServer = require('./socketServer ')
// This is a Map
let myNameIOClients = socketServer.myNameIOClients
// We can easily turn it into an array if needed
let myNameIOClientsArray = Array.from(socketServer.myNameIOClients)
Combing through the documentation but no luck. I'm trying to emit to a single client/user rather than everyone.
I read several other questions about this, most have no answer or point to older solutions. Any help would be appreciated.
The following works but emits to everyone on the site rather than the individual user...
SERVER:
//Socket.io
const http = require('http').Server(app);
const io = require('socket.io')(http);
app.post('/login', (req, res) => {
const email = cryptonize.encrypt(req.body.email);
const password = cryptonize.encrypt(req.body.password);
io.emit('login success', email, password);
});
CLIENT:
const socket = io();
socket.on('login success', (user, token, auth) => {
console.log(`user:${user}, password:${password});
});
I've tried "socket.emit" as mentioned in the socket.io cheat sheet, but it's coming back as undefined on the server. Probably something really simple I'm missing, just not seeing it.
I don't think that is the intended use of socket.io.
In your case, a simple res.end(...) will do (at least based on what you showed us).
app.post('/login', (req, res) => {
const email = cryptonize.encrypt(req.body.email);
const password = cryptonize.encrypt(req.body.password);
res.end(/* data */);
});
Read the docs about res.end().
If you really need to emit to a single socket, you need more work:
Use socket.io's rooms or namespace.
Get target socket's id.
Emit using the socket id.
Here's an example using default namespace:
Server
const IO = require('socket.io');
const io = IO(server);
// Default namespace is '/'
const namespacedIO = io.of('/');
io.on('connection', socket => {
socket.on('send', data => {
const targetSocket = namespacedIO.connected[data.socketID];
targetSocket.emit('received', data.value);
});
});
Client
const socket = io();
submit.addEventListener('click', function(){
socket.emit('send', {
socketID: socket.id, // IMPORTANT: to get the source socket ID
value: input.value
});
})
socket.on('received', function(data){
console.log(`Data "${data}" is received at server.'`);
});
Here's what I ended up doing, for anyone else trying to figure this out.
SERVER:
//Socket.io
const http = require('http').Server(app);
const io = require('socket.io')(http);
app.post('/login', (req, res) => {
const email = cryptonize.encrypt(req.body.email);
const password = cryptonize.encrypt(req.body.password);
const socketid = req.query.socket;
io.sockets.connected[socketid].emit('login success', email, password);
});
CLIENT:
const socket = io();
let socketid;
socket.on('connect', () => socketid = socket.io.engine.id);
CLIENT cont..
Then I just added a "socketid" query to my posts as they're generated.
//XHR Setup
const xhr = new XMLHttpRequest();
let response, status, readyState;
xhr.onreadystatechange = () => {
if (xhr.status === 200 && xhr.readyState === 4) response = xhr.response;
};
//XHR POST
const post = ({ url, callback, data }) => {
xhr.open('POST', `${url}&socketid=${socketid}`, true), xhr.setRequestHeader('Content-type', 'application/json'), xhr.send(data);
if (callback) callback();
console.log(`${url}&socketid=${socketid}`);
}
First of all I would like to say that I am new in senecajs.
I am testing this configuration.
I have configured Senecjs microservice running on port 9007, which is running and handling request correctly. When I request this service directly I receive response after cca 10s (it is request for oracle db data).
But when I request for same data but through the Hapi + Seneca-web I receive this error: "statusCode":504,"error":"Gateway Time-out"
["client","invalid_origin",{"port":9007,"pin":"mc:bankgtw","pg":"mc:bankgtw","type":"web","id":"pg:mc:bankgtw,pin:mc:bankgtw,port:9007","role":"transport","hook":"client","plugin$":{"name":"client$"},"fatal$":true,"meta$":{"mi":"wbn8u45tb7uh","tx":"o3f8eyia3f4n","id":"wbn8u45tb7uh/o3f8eyia3f4n","pattern":"hook:client,role:transport,type:web","action":"(q1yytemztu3k)","plugin_name":"transport","plugin_tag":"-","prior":{"chain":[],"entry":true,"depth":0},"start":1487199713842,"sync":true},"tx$":"o3f8eyia3f4n","host":"0.0.0.0","path":"/act","protocol":"http","timeout":5555,"max_listen_attempts":11,"attempt_delay":222,"serverOptions":{}},{"kind":"res","res":null,"error":{"isBoom":true,"isServer":true,"output":{"statusCode":504,"payload":{**"statusCode":504,"error":"Gateway Time-out**","message":"Client request timeout"},"headers":{}}},"sync":true,"time":{"client_recv":1487199799177}}]
A few seconds before microservice return data.
And this is my configuration:
const Hapi = require('hapi');
const Seneca = require('seneca');
const SenecaWeb = require('seneca-web');
const config = {
adapter: require('seneca-web-adapter-hapi'),
context: (() => {
const server = new Hapi.Server();
server.connection({
port: 3001,
routes: {
cors: true,
payload:{timeout:60000},
timeout:{server: 60000, socket:90000}
}
});
server.route({
path: '/routes',
method: 'get',
handler: (request, reply) => {
const routes = server.table()[0].table.map(route => {
return {
path: route.path,
method: route.method.toUpperCase(),
description: route.settings.description,
tags: route.settings.tags,
vhost: route.settings.vhost,
cors: route.settings.cors,
jsonp: route.settings.jsonp,
server: server.info
}
})
reply(routes)
}
});
return server;
})()
};
const seneca = Seneca({timeout: 99999})
.use(SenecaWeb, config)
.use(require('./hapi_api.js'))
.client({ port:9007, pin:'mc:bankgtw' })
.ready(() => {
const server = seneca.export('web/context')();
server.start(() => {
server.log('server started on: ' + server.info.uri);
});
});
What I am doing wrong or what timeout is causing this?
I've had the same issue, fixed it, but its VERY BAD PRACTICE.
Go to 'transport.js' at seneca-transport folder.
You will see 'timeout: 5555'
Go ahead and change that to whatever you need.
I'm not sure why this is not getting USER defaults.
To the best of my knowledge, this is referring to client timeout. make sure you still use server timeout.
I've looked around and it seems as if all the ways to implement SSEs in Node.js are through more complex code, but it seems like there should be an easier way to send and receive SSEs. Are there any APIs or modules that make this simpler?
Here is an express server that sends one Server-Sent Event (SSE) per second, counting down from 10 to 0:
const express = require('express')
const app = express()
app.use(express.static('public'))
app.get('/countdown', function(req, res) {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
})
countdown(res, 10)
})
function countdown(res, count) {
res.write("data: " + count + "\n\n")
if (count)
setTimeout(() => countdown(res, count-1), 1000)
else
res.end()
}
app.listen(3000, () => console.log('SSE app listening on port 3000!'))
Put the above code into a file (index.js) and run it: node index
Next, put the following HTML into a file (public/index.html):
<html>
<head>
<script>
if (!!window.EventSource) {
var source = new EventSource('/countdown')
source.addEventListener('message', function(e) {
document.getElementById('data').innerHTML = e.data
}, false)
source.addEventListener('open', function(e) {
document.getElementById('state').innerHTML = "Connected"
}, false)
source.addEventListener('error', function(e) {
const id_state = document.getElementById('state')
if (e.eventPhase == EventSource.CLOSED)
source.close()
if (e.target.readyState == EventSource.CLOSED) {
id_state.innerHTML = "Disconnected"
}
else if (e.target.readyState == EventSource.CONNECTING) {
id_state.innerHTML = "Connecting..."
}
}, false)
} else {
console.log("Your browser doesn't support SSE")
}
</script>
</head>
<body>
<h1>SSE: <span id="state"></span></h1>
<h3>Data: <span id="data"></span></h3>
</body>
</html>
In your browser, open localhost:3000 and watch the SSE countdown.
I'm adding a simple implementation of SSE here. It's just one Node.js file.
You can have a look at the result here: https://glossy-ox.glitch.me/
const http = require('http');
const port = process.env.PORT || 3000;
const server = http.createServer((req, res) => {
// Server-sent events endpoint
if (req.url === '/events') {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
...(req.httpVersionMajor === 1 && { 'Connection': 'keep-alive' })
});
const refreshRate = 1000; // in milliseconds
return setInterval(() => {
const id = Date.now();
const data = `Hello World ${id}`;
const message =
`retry: ${refreshRate}\nid:${id}\ndata: ${data}\n\n`;
res.write(message);
}, refreshRate);
}
// Client side
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(`
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>SSE</title>
</head>
<body>
<pre id="log"></pre>
</body>
<script>
var eventSource = new EventSource('/events');
eventSource.onmessage = function(event) {
document.getElementById('log').innerHTML += event.data + '<br>';
};
</script>
</html>
`);
});
server.listen(port);
server.on('error', (err) => {
console.log(err);
process.exit(1);
});
server.on('listening', () => {
console.log(`Listening on port ${port}`);
});
If you're using express this is the easiest way https://www.npmjs.com/package/express-sse
on BE:
const SSE = require('express-sse');
const sse = new SSE();
...
app.get('/sse', sse.init);
...
sse.send('message', 'event-name');
on FE:
const EventSource = require('eventsource');
const es = new EventSource('http://localhost:3000/sse');
es.addEventListener('event-name', function (message) {
console.log('message:', message)
});
I found SSE implementation in node.js.
Github link: https://github.com/einaros/sse.js
NPM module:https://www.npmjs.com/package/sse
Will above link helps you ?
**client.js**
var eventSource = new EventSource("/route/events");
eventSource.addEventListner("ping", function(e){log(e.data)});
//if no events specified
eventSource.addEventListner("message", function(e){log(e.data)});
**server.js**
http.createServer((req, res)=>{
if(req.url.indexOf("/route/events")>=){
res.setHeader('Connection', 'keep-alive');
res.setHeader("Cache-Control", "no-cache");
res.setHeader("Content-Type", "text/event-stream");
let event = "event: ping";
let id = `id: ${Date.now()}`;
let data = {
message:`hello #${new Date().toString()}`
}
data = "data: "+JSON.stringify(data);
res.end(`${event}\n${id}\n${data}\n\n`);
}
}).listen(PORT)
After looking at the other answers I finally got this working, but what I ended up having to do was a little different.
[package.json] Use express-sse:
The exact version of express-sse is very important. The latest tries to use res.flush(), but fails and crashes the http server.
"express-sse": "0.5.1",
[Terminal] Install express-sse:
npm install
[app.js] Use the router:
app.use(app.baseUri, require('./lib/server-sent-events').router);
[server-sent-events.js] Create sse library:
The call to pause() is the equivalent of flush(), which was removed from express. It ensures you'll keep getting messages as they are sent.
var express = require('express');
const SSE = require('express-sse');
const sse = new SSE();
var router = express.Router();
router.get('/sse', sse.init)
module.exports = {
send,
router
};
async function send(message) {
sse.send(message.toProperCase(), 'message');
await pause();
}
function pause() {
return new Promise((resolve, reject) => {
setImmediate(resolve)
})
}
[your-router.js] Use the sse library and call send:
var express = require('express');
var serverSentEvents = require('../lib/server-sent-events');
var router = express.Router();
router.get('/somepath', yourhandler);
module.exports = router;
async function yourhandler (req, res, next) {
await serverSentEvents.send('hello sse!'); // <<<<<
}
[your-client-side.js] Receive the sse updates:
I recommend you keep the event.data.replace(/"/g,'') because express-sse tacks on enclosing quotes and we don't want those.
const eventSource = new EventSource('http://yourserver/sse');
eventSource.onmessage = function(event) {
document.getElementById("result").innerHTML = event.data.replace(/"/g,'') + '...';
};
You should be able to do such a thing using Socket.io. First, you will need to install it with npm install socket.io. From there, in your code you will want to have var io = require(socket.io);
You can see more in-depth examples given by Socket.IO
You could use something like this on the server:
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('../..')(server);
var port = process.env.PORT || 3000;
server.listen(port, function () {
console.log('Server listening at port ' + port);
});
app.use(express.static(__dirname + '/public'));
io.on('connection', function (socket) {
socket.emit('EVENT_NAME', {data});
});
And something like this on the client:
<script src="socket_src_file_path_here"></script>
<script>
var socket = io('http://localhost');
socket.on('EVENT_NAME', function (data) {
console.log(data);
//Do whatever you want with the data on the client
});
</script>
I am trying to build a simple node.js based streaming API. All I want to do is as I hit the server url, the output should stream a set of test data(JSON) like twitter streaming API.
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(8083);
app.get('/', function (req, res) {
res.write(io.on('connection', function (socket) {
socket.emit('item', { hello: 'world' });
}));
});
So, If i do curl http://localhost:8083/, I want output something like:
$ curl http://localhost:8083/
{hello: 'world'}
{hello: 'world'}
{hello: 'world'}
{hello: 'world'}
...
I am new to node.js and web sockets. I might be horribly wrong on the basics of how node works, let me know the best solution.
First, it's better to put the JSONStream part inside a middleware like so:
var _ = require('lodash');
// https://github.com/smurthas/Express-JSONStream/blob/master/index.js
function jsonStream(bytes) {
return function jsonStream(req, res, next) {
// for pushing out jsonstream data via a GET request
var first = true;
var noop = function () {};
res.jsonStream = function (object, f) {
f = _.isFunction(f) ? f : noop;
if (!(object && object instanceof Object)) {
return f();
}
try {
if (first) {
first = false;
res.writeHead(200, {
'Content-Type': 'application/json',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
}
res.write(JSON.stringify(object) + '\n');
} catch (err) {
return _.defer(f.bind(null, err));
}
f();
};
next();
};
}
Then, let's say you want to be notified via this API each time someone connects to socket.io
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var _ = require('lodash');
var EventEmitter = require('events').EventEmitter;
server.listen(8083);
var mediator = new EventEmitter();
io.on('connection', function (socket) {
mediator.emit('io:connection:new', socket);
});
// the second parameter, specify an array of middleware,
// here we use our previously defined jsonStream
app.get('/', [jsonStream()], function (req, res) {
function onNewConnection(socket) {
res.jsonStream({
type: 'newConnection',
message: 'got a new connection',
socket: {
id: socket.id
}
});
}
// bind `onNewConnection` on the mediator, we have to use an mediator gateway
// because socket.io does not offer a nice implementation of "removeListener" in 1.1.0
// this way each time someone will connect to socket.io
// the current route will add an entry in the stream
mediator.on('io:connection:new', onNewConnection);
// unbind `onNewConnection` from the mediator
// when the user disconnects
req.on('close', function () {
mediator.removeListener('connection', onNewConnection);
});
res.jsonStream({
type: 'welcome',
message: 'waiting for connection'
});
});
Finally, if you want to test this code without connecting to socket.io use the following simulator:
// Simulate socket.io connections using mediator
(function simulate() {
var dummySocket = {
id: ~~(Math.random() * 1000)
};
mediator.emit('io:connection:new', dummySocket);
setTimeout(simulate, Math.random() * 1000);
})();