Start from our simple express server
// ========================
// ==== Express server ====
// ========================
var express = require("express");
var app = express();
app.get("/static/:staticFilename", function (request, response) {
response.sendfile("static/" + request.params.staticFilename);
});
app.listen(8889);
// ========================
// === Socket.io server ===
// ========================
// We'll write all our socket.io code here
Let's instantiate a socket server in the same app.js, and run that on port 8888. Note that now we will have two distinct servers, socket.io on 8888 and express on 8889.
var io = require('socket.io').listen(8888);
Everything on socket.io happens after a client connects
io.sockets.on("connection", function(socket) {
Listen for a msg event
socket.on('msg', function(data) {
Send an event back to the sender
// confirm success to sender
socket.emit('status', { success: 'true'});
Send an event to all other connected clients
// broadcast message to everyone else
io.sockets.emit('newmsg', { body: data.body });
});
});
The client side code will be running in the user's browser. The page itself can be served using the express server on port 8889.
Include the socket.io javascript, automatically served from your socket.io server on port 8888
<script src="http://localhost:8888/socket.io/socket.io.js"></script>
<script>
Make the connection
var socket = io.connect("http://localhost:8888");
Send a message when form is submitted
$("#chatform").submit(function() {
// send the msg event, with some data
socket.emit('msg', {body: $("#chatbody").val() });
return false;
});
Alert when sending is successful, by listening to the status event
socket.on("status", function(data) {
if (data.success) {
alert("Message successfully sent");
} else {
alert("Message failed to send");
}
});
Append message to DOM when receiving messages, by listening to the newmsg event
socket.on("newmsg", function(data) {
$("#messages").append($("<li>").html(data.body));
});
</script>