I have the following code
var app = require('express')();
var http = require('http');
var server = http.createServer();
var socket = require('socket.io');
var io = socket.listen( server );
io.sockets.on('connection', function(socket) {
console.log('socket connected');
socket.broadcast.emit('newUser', 'New User Joined, Say Hi :D');
socket.on('serverEmit',function(msg) {
console.log('works');
});
socket.on('chatMessage', function(msg) {
io.emit('server_emit', msg);
console.log(msg);
});
});
server.listen(3500, function() {
console.log('listening on *:3500');
});
So my question is how to add an emit function outside of this socket connection. For example, if I have a get request like below
app.get('/link',function(req,res) {
io.sockets.emit('trigger','triggered'); // Process I want to make
});
Thanks in advance.
Socket.IO can be used based on the Express server just as easily as it can run on a standard Node HTTP server. In this section, we will fire the Express server and ensure that it can talk to the client side via Socket.IO.
socket. emit - This method is responsible for sending messages. socket. on - This method is responsible for listening for incoming messages.
You almost had it:
it's io.emit('trigger','triggered');
And if you need to emit to a namespace you can do:
const namespace = io.of("name_of_your_namespace");
namespace.emit('trigger','triggered');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With