Ok trying my hand at NodeJS and socket.io and have run into a problem. I have NodeJS and Socket.io installed and running on my localhost. At present I have the following setup:
server.js
// Require HTTP module (to start server) and Socket.IO
var http = require('http'), io = require('socket.io');
// Start the server at port 8080
var server = http.createServer(function(req, res){
// Send HTML headers and message
res.writeHead(200,{ 'Content-Type': 'text/html' });
res.end('<h1>NodeJS Server Online</h1>');
});
server.listen(8080);
// Create a Socket.IO instance, passing it our server
var socketserver = io.listen(server);
// Add a connect listener
socketserver.on('connection', function(socket){
socket.emit("server ready");
socket.on('test', function (msg) {
socket.broadcast.emit('TEST:', msg);
console.log(msg);
});
socket.on('user message', function (msg) {
socket.broadcast.emit('user message', msg);
console.log(msg);
});
});
client.js
$(document).ready(function() {
// Stuff to do as soon as the DOM is ready;
var socket = io.connect('http://localhost',{port:8080});
socket.on('server ready',function() {
messages.append("<li>Server Ready...</li>");
console.log("Server Ready");
});
// Add a connect listener
socket.on('connect',function() {
messages.append("<li>Connected...</li>");
console.log("connected");
socket.emit('test',"Just testing");
});
});
Server starts fine, but my problem is that the server.js does not fire the socket.emit("server ready"); line. The client side code works fine as in terminal.app on testing my server outputs this line:
websocket received data packet 5:::{"name":"test","args":["Just testing"]}
What am I missing? Why isn't the server side stuff firing?
I updated socket.io to 0.7.2 and then slightly modified your example to use express. The code below was able to receive the "server ready" event.
Node Server:
var http = require('http'),
express = require('express');
var app = module.exports = express.createServer();
// Configuration
app.configure(function(){
app.use(express.static(__dirname + '/public'));
});
app.listen(9000);
console.log("server started");
// socket.io
var io = require('socket.io').listen(app);
io.sockets.on('connection', function(socket){
socket.emit('server ready', {msg: 'hi'}) ;
});
Web Page (/sock.html):
<html>
<body>
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect();
socket.on('server ready', function(data){ console.log('server ready!'); }) ;
</script>
</body>
</html>
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