Trying to execute the simplest of targeted messaging in socket.io with no success. According to the documentation for socket.io with express.js you can target a message to a single user socket with socket.to(socket.id).emit('event name', 'message')
I have already read the socket.io docs from start to finish and other stack overflow Q/A here and here and here. Some of the solutions I find involve creating rooms and messaging those rooms, but the objective of this question is to send a message to the socket id using socket.to(socket.id).emit('event name', 'message')
as given in the socket.io documention.
I'm using node v6.11.2, express 4.15.2 and socket.io 2.0.3.
The client and server code are taken almost verbatim from https://socket.io/get-started/chat/ with minor changes while I experiment.
index.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
io.on('connection', function(socket){
console.log(req.ip+' connected');
socket.on('chat message', function(msg){
console.log(socket.id);//logs the socket id. Something like 'AUCyM1tnpinCfvfeAAAB'
console.log(msg);//logs whatever the message was, so I know the server is receiving the message
socket.to(socket.id).emit('chat message', 'Nothing is happening here.');
});
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
index.html
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
...
</style>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(function () {
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
});
</script>
</body>
</html>
Change this:
socket.to(socket.id).emit(...)
to this:
socket.emit(...)
Here's an explanation. socket.to(socket.id).emit(...)
will broadcast to the room named socket.id
. That's OK, there is a room with that name and socket
is the only member. But, socket.to()
sends to all members of that room EXCEPT socket
so there's nobody to send it to.
So, if you want to send just to socket
, then just use socket.emit()
.
Here's a quote from the socket.io doc for socket.to()
:
Sets a modifier for a subsequent event emission that the event will only be broadcasted to clients that have joined the given room (the socket itself being excluded).
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