Reputation: 43
I am trying to make a chat app with socket.io and I've run into a weird occurrence: my server receives the messages that I sent but the client doesn't.
Server Code:
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '\\index.html');
});
io.on('connection',function(socket){
socket.on('chat message', function(msg){
io.emit(msg)
console.log('message: ' + msg)
})
})
http.listen(3002,function(){
console.log('listening on 3002');
});
And here is the client's code:
<script>
$(function () {
var socket = io();
$('form').submit(function(e){
e.preventDefault(); // prevents page reloading
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
console.log(msg)
// $('#messages').append($('<li>').text(msg));
});
});
</script>
where #m is am input field with the message I want to send
Upvotes: 2
Views: 140
Reputation: 17654
You have to emit an event name with some data :
From the docs :
socket.emit(eventName[, …args][, ack])
on the Server :
io.on('connection',function(socket){
socket.on('chat message', function(msg){
io.emit('newMessage', msg )
// ^^^^^^^^^^ ^^^^
// event name data
console.log('message: ' + msg)
})
})
on the client :
socket.on('newMessage', function(msg){
console.log(msg)
});
Upvotes: 1