i realize this post is several years old now, but sometimes certified newbies such as myself need a working example that is totally stripped down to the absolute most simplest form.
every simple socket.io example i could find involved http.createServer(). but what if you want to include a bit of socket.io magic in an existing webpage? here is the absolute easiest and smallest example i could come up with.
this just returns a string passed from the console UPPERCASED.
app.js
var http = require('http');
var app = http.createServer(function(req, res) {
console.log('createServer');
});
app.listen(3000);
var io = require('socket.io').listen(app);
io.on('connection', function(socket) {
io.emit('Server 2 Client Message', 'Welcome!' );
socket.on('Client 2 Server Message', function(message) {
console.log(message);
io.emit('Server 2 Client Message', message.toUpperCase() ); //upcase it
});
});
index.html:
<!doctype html>
<html>
<head>
<script type='text/javascript' src='http://localhost:3000/socket.io/socket.io.js'></script>
<script type='text/javascript'>
var socket = io.connect(':3000');
// optionally use io('http://localhost:3000');
// but make *SURE* it matches the jScript src
socket.on ('Server 2 Client Message',
function(messageFromServer) {
console.log ('server said: ' + messageFromServer);
});
</script>
</head>
<body>
<h5>Worlds smallest Socket.io example to uppercase strings</h5>
<p>
<a href='#' onClick="javascript:socket.emit('Client 2 Server Message', 'return UPPERCASED in the console');">return UPPERCASED in the console</a>
<br />
socket.emit('Client 2 Server Message', 'try cut/paste this command in your console!');
</p>
</body>
</html>
to run:
npm init; // accept defaults
npm install socket.io http --save ;
node app.js &
use something like this port test to ensure your port is open.
now browse to http://localhost/index.html and use your browser console to send messages back to the server.
at best guess, when using http.createServer, it changes the following two lines for you:
<script type='text/javascript' src='/socket.io/socket.io.js'></script>
var socket = io();
i hope this very simple example spares my fellow newbies some struggling. and please notice that i stayed away from using "reserved word" looking user-defined variable names for my socket definitions.