npm install faye
The faye module is built on the bayeux protocol and passes messages to all connected clients. The server code will handle two endpoints - the faye endpoint on port 8000 and a web server on port 9000 to server up the user's page.
application.js:
var express = require('express');
var faye = require('faye');
// Create the faye server
var bayeux = new faye.NodeAdapter({mount: '/faye', timeout: 45});
bayeux.listen(8000);
// Create the web server
var server = express.createServer();
server.configure(function() {
server.use(express.static(__dirname + '/public'));
});
server.listen(9000);
console.log('Web Server listening on 9000, Bayeux on 8000');
The html page has a simple form to allow the user to input a message and some javascript to hook up the events and publish the messages.
public/index.html:
<html>
<head>
<script type="text/javascript" src="http://localhost:8000/faye.js"></script>
</head>
<body>
<div style="width:800px; margin:5px; padding:5px;">
<input id="message" type="text" size="70"></input>
<input id="post" type="submit" value="Post Message"></input>
<ul id="messages" style="border:1px solid Silver; padding:5px 0;"></ul>
</div>
<script type="text/javascript">
// Create a "unique" id for this client (hack)
var id = Math.floor(Math.random() * 100000);
// Create the client and connect to the server
var client = new Faye.Client('http://localhost:8000/faye');
client.connect();
// Subscribe to the chat channel to receive messages
client.subscribe('/faye/chat', function(message) {
var messages = document.getElementById('messages');
messages.innerHTML = '<li style="margin-left:20px;">' +
message.text + '</li>' + messages.innerHTML;
});
// Handle the button click to allow users to post messages
var button = document.getElementById('post');
button.onclick = function() {
var message = document.getElementById('message');
if (message.value != '') {
client.publish('/faye/chat', { text: id + ': ' +
message.value })
message.value = '';
message.focus();
}
return false;
}
</script>
</body>
</html>
A huge advantage of node is the ability to share code between applications in the browser and applications in the server. Let's add a server "bot" that will respond to chat messages. We do this with the same code the browser does:
// Create a client on the server
// Code is nearly identical to browser
bayeux.getClient().subscribe('/faye/chat', function(message) {
if (message.text.indexOf('admin:pid') > -1) {
bayeux.getClient().publish('/faye/chat',
{ text:'admin pid is ' + process.pid }
);
}
});
No comments:
Post a Comment