I am trying to get a basic chat application running that uses node.js, express, and socket.io.
I've successfully got everything running to where I don't get any errors on the server side or client side. However, the application doesn't work.
I am supposed to be able to open two browser windows and chat with myself. I type in the text box to send a chat message to myself but nothing is received. I am pretty sure nothing is sent either. Using FireBug I don't see any new requests being sent over the network. However, using Firebug I also see that all the requested include files are being served correctly to the browser. There are only three - index.html, socket.io.js, and jquery.min.js.
Here is a link to the tutorial I am using: http://philmunt.com/post/15643013618/node-js-socket-io-chat-application-tutorial
With the server.js file I modified it a little to get it working. The main problem was that my browser was not receiving socket.io.js so I added a path to allow server.js to know where it is. Like this: app.get('/sio/socket.io.js', function (req, res) {........ Could that be my problem?
Here is the server code - server.js:
var express = require('express'), app = express(), http = require('http'), server = http.createServer(app), io = require('socket.io').listen(server);
// listen for new web clients:
server.listen(8080);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
app.get('/sio/socket.io.js', function (req, res) {
res.sendfile('/root/nodejs/node-v0.10.0/node_modules/socket.io/lib/socket.io.js');
});
io.sockets.on('connection', function (socket) { socket.on('sendMessage', function (data) { socket.broadcast.emit('message', data); socket.emit('message', { text: '<strong>'+data.text+'</strong>' });
});
});
Here is the index.html file:
<html>
<body>
<script src="/sio/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
var socket = io.connect('http://localhost');
socket.on('message', function (data) {
$('#chat').append(data.text + '<br />');
});
$('#send').click(function () {
socket.emit('sendMessage', { text: $('#text').val() });
$('text').val('');
});
});
</script>
<div id="chat" style="width: 500px; height: 300px; border: 1px solid black">
</div>
<input type="text" name="text" id="text">
<input type="button" name="send" id="send" value="send">
</body>
</html>
Remove the app.get(socketstuff) part, you don't need that as the js file is made available for you with
<script src="/socket.io/socket.io.js"></script>
and change your socket variable to:
var socket = io.connect();