Reputation: 1975
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.
Upvotes: 2
Views: 600
Reputation: 1698
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. :)
Upvotes: 0
Reputation: 181
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.
Upvotes: 2