Reputation: 5
I'm a newbie in NodeJS and I just started creating a simple chat app with Express and Socket.io but It the "message" emit part is not working (socket.on('connect') works!). The alert "OK" works fine but console.log doest nothing.
Here is my code:
App.js
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
app.get('/', function(req, res,next) {
res.sendFile(__dirname + '/index.html');
});
app.get('/test', function(req, res,next) {
res.render('HALLO ');
});
server.listen(4200);
io.on('connection', function(client) {
// var address = io.handshake.address;
console.log('Ein neuer Client hat sich zum Chat verbunden! IP: ')
});
io.on('sendmsg', function(data) {
console.log(data);
});
Index.html
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script>
var socket = io.connect('http://localhost:4200');
function sendMsg(){
alert("OK");
socket.emit('sendmsg', document.getElementById("text").value);
}
</script>
<h2>Awesome Chat by Simon</h2>
<br>
<input type="text" id="text">
<input type="button" onclick="sendMsg()" value="Senden">
Upvotes: 0
Views: 2293
Reputation: 50954
You should move your handler inside the on connection
function like this:
io.on('connection', function(client) {
// var address = io.handshake.address;
console.log('Ein neuer Client hat sich zum Chat verbunden! IP: ');
client.on('sendmsg', function(data) { // Move this part inside the connection function
console.log(data);
});
});
Upvotes: 1
Reputation: 663
Try doing this way.
io.on('connection', function(client) {
console.log('Ein neuer Client hat sich zum Chat verbunden! IP: ')
client.on('sendmsg', function(data) {
console.log(data);
});
});
Upvotes: 0
Reputation: 138537
The event gets triggered on the socket (client
) not on the server:
io.on('connection', function(client) {
// var address = io.handshake.address;
console.log('Ein neuer Client hat sich zum Chat verbunden! IP: ');
client.on("sendmsg", console.log);
});
Upvotes: 0
Reputation: 6233
You listen on individual socket
. Move your listener from io
to client
io.on('connection', function(client) {
// var address = io.handshake.address;
console.log('Ein neuer Client hat sich zum Chat verbunden! IP: ')
client.on('sendmsg', function(data) {
console.log(data);
});
});
Upvotes: 4