Receive socket.io messages outside of connection - node.js

I know that messages can be sent outside the socket connection code block. How can I receive messages from the client the same way?
// Create socket.io server attached to current HTTP server
var io = require('socket.io')(server);
// When connection is made, set up some definitions for the server's connections
io.on('connection', (socket) => {
console.log('Local server connected...');
socket.on('disconnect', () => {
console.log('Local server disconnected...');
});
// I can receive messages here
socket.on('sendToRemote', function (data) {
console.log(data);
});
});
// Messages can be received outside the socket code using this syntax:
io.of('/').emit('runCamera', "Client connected...");
// I can't receive messages here...
// How can the server receive messages outside the socket code?
// I tried using the code below but it didn't work.
// Syntax compiles but doesn't work like the one above.
io.of('/').on('sendToRemote', function (data) {
console.log(data);
});

You need to have a socket to get messages from. You can emit to a room because it's tracking all the sockets connected to that room.
So to get messages only in a specific room:
io.of('/').on('connection', function (socket) {
socket.on("sendToRemote", function (data) {
console.log(data);
});
});

Related

How to emit data from socket-IO client to socket-IO server?

so I am developing an small application that need a bi-directional channel to transmit data between client and server.
I have no problem to send sata from server to client. Works just fine. But , the other way around is not working. for some reason , sending data from client to client does not work.
here is the client.js
let io = require('socket.io-client');
let socket = io.connect("http://localhost:5000/", {
reconnection: false
});
socket.on('connect', function() {
console.log('Connected to server');
socket.emit('data', 'data is emitted !')
});
and here is server.js :
var io = require('socket.io').listen(process.env.port||5000);
io.on('connection',function () {
console.log('client connected');
io.on('data',function (data) {
console.log(`data received is '${data}'`)
})
});
What am I missing ?
The server code needs to listen for incoming events from a particular socket.on(), not io.on(). io is the server. It gets notified of new connections, but not of individual messages on a given connection. You have to listen to events on a particular socket to receive data from the client.
So, change to this (change io to socket in one place and add socket argument to the io.on('connection', function(socket) ()); handler (see the two places that socket was added below):
const io = require('socket.io').listen(process.env.port||5000);
io.on('connection', function(socket) {
console.log('client connected');
// listen for incoming data msg on this newly connected socket
socket.on('data',function (data) {
console.log(`data received is '${data}'`)
});
});
Note: the addition of socket in two places.

socket.io emit to one client not working

I'm using socket.io 1.7.3 version. Server code:
io.on('connection', function (socket) {
console.log(socket.id); // CdnNBVe9ktJmMcb1AAAA
socket.to(socket.id).emit('something');
socket.emit('something'); // if I do it without to, it works but to all clients
console.log(socket.rooms); // { CdnNBVe9ktJmMcb1AAAA 'CdnNBVe9ktJmMcb1AAAA' }
});
Client:
<script src="/socket.io/socket.io.js"></script>
var socket = io.connect(..);
socket.on('connect', function() {
console.log(socket.id); // CdnNBVe9ktJmMcb1AAAA
socket.on('something', function() {
alert('it works');
});
});
Why it doesn't work? I'm not getting any alert although all console.logs seems to be correct.
To send a message to the particular client, you must provide socket.id of that client to the server and at the server side socket.io takes care of delivering that message by using,
socket.broadcast.to('ID').emit( 'send msg', {somedata : somedata_server} );
In your code
socket.broadcast.to(socket.id).emit('something');

node.js server socket.io-client with SSL

I try to setup two node.js servers communication with each other over socket.io. The node servers use SSL, but I don't get it running. I do not get any feedback, its close to this:
Node.js socket.io-client connect_failed / connect_error event
This will not work. No response.
var clientio = require('socket.io-client');
console.log('Trying stuff ...');
// the channel does not exist
var socket = clientio.connect( 'http://localhost:4000/news' );
// I expect this event to be triggered
socket.on('connect_failed', function(){
console.log('Connection Failed');
});
socket.on('connect', function(){
console.log('Connected');
});
socket.on('disconnect', function () {
console.log('Disconnected');
});
but if I try:
// Bind to the news namespace, also get the underlying socket
var ns_news = clientio.connect( 'https://localhost:9000' );
var socket = ns_news.socket
// Global events are bound against socket
socket.on('connect_failed', function(){
console.log('Connection Failed');
});
socket.on('connect', function(){
console.log('Connected');
});
socket.on('disconnect', function () {
console.log('Disconnected');
});
// Your events are bound against your namespace(s)
ns_news.on('myevent', function() {
// Custom event code here
});
I can see that ns_news has no element socket, so I get:
TypeError: Cannot call method 'on' of undefined
So how do I connect these two servers with feedback if the connection is successful or not?
And my following question would be:
How can these two servers authenticate to each other?
Means: Server A says to server B:
- hey, gimme that secret string
And Server B checks the certificate of server A and if it's ok
- here's the string
How do I do it with node?

Sending a message to the client on connection using node and socket io

How do i send a message to a specific client, more specifically, the client that has just connected to the app without broadcasting to the rest of the visitors that are already on the site?
io.sockets.on('connection', function(client) {
});
Seems to broadcast to everyone every time a new visitors connects.
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.emit('greetings', { greeting:'hello, new visitor' });
socket.on('greetingFromVisitor', function (data) {
console.log(data);
});
});

Why is my Socket.io Express app just sending to the 'sender's' client?

I'm trying to write a basic chat application with Node.js (Express), and Socket.io. Everything 'seems' to be working, but my socket server seems to be only 'sending' the message back to the original sender. Here is my socket code:
var client = io.listen(app);
client.sockets.on('connection', function (socket) {
socket.on('message', function (data) {
console.log(data);
socket.send(data);
});
});
And here is my client side code:
$(document).ready(function() {
var socket = new io.connect('http://localhost:3000');
socket.on('connect', function() {
socket.send('A client connected.');
});
socket.on('message', function(message) {
$('#messages').html('<p>' + message + '</p>' + $('#messages').html());
console.log(socket);
});
$('input').keydown(function(event) {
if(event.keyCode === 13) {
socket.send($('input').val());
$('input').val('');
}
});
});
Help is appreciated.
Use client.sockets.emit instead of socket.emit. It will emit to every connected client (broadcast), using the socket object only sends to the specific client.
Server side, I think you want:
socket.broadcast.emit(data);
instead of:
socket.send(data);
See "Broadcasting Messages" at the bottom of the "How to use" page. :)

Resources