soderlind.no

I code for fun

Node.js

| 1 Comment

If you haven’t looked at Node.js, you should. Node.js is “evented I/O for V8 javascript”.  With Node.js (and its well documented api) you can write extremely high performance non-blocking event driven network servers in JavaScript.

Here’s a simple chat server and client I wrote using Node.js, Faye and the Connect middleware.


app.js (the chat server, run using connect app.js -p 8080):

var Faye = require('./lib/faye-node');

var fayeServer = new Faye.NodeAdapter({
  mount:    '/faye',
  timeout:  45
});
var cometServer = {
    handle: function(req, res, next){
                  if (fayeServer.call(req, res)) return;

                  // Handle non-Faye requests
                  res.writeHead(200, {'Content-Type': 'text/plain'});
                  res.end('Hello, non-Faye request');
    }
};

module.exports = require('./lib/connect').createServer([
    { module: cometServer }
]);

client.html:

<html>
	<head>
		<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js'></script>
		<script type="text/javascript" src="http://localhost:8080/faye.js"></script>
		<script type="text/javascript">
			$(document).ready(function() {
			    var client = new Faye.Client('http://localhost:8080/faye');
				// receive chat messages
				client.subscribe('/messages', function(message) {
					var p = $("<div class='chat' style='display:block;'><div class='content'>" + message.text + "</div></div>");
					$('#chats').append(p);
					$('#chats').scrollTop($('#chats').attr("scrollHeight"));
				});
		    	// send message to the chat server
				$("#pubmsg").keyup(function(event) {
				  	if (event.keyCode == '13' || event.keyCode == undefined) {
				    	client.publish('/messages', {
						  text: $("#pubmsg").val()
						});
						$("#pubmsg").val("").focus();
				  	}
				});	

				$('#pubsend').click(function() {
				  $('#pubmsg').keyup();
				});
		    });
		</script>
		<style type="text/css">
			#chats {
				width: 300px;
				height:200px;
				border: solid 1px #000;
				overflow:auto;
			}
		</style>
	</head>
	<body>
		<div id="chats"></div>
		<input type="text" id="pubmsg" value="" style="width:296px;margin:0px"/> <input type="button" id="pubsend" value="send" />
	</body>
</html>

One Comment

  1. wow! very interesting, thank’s

Click on a tab to select how you'd like to leave your comment

Leave a Reply

Required fields are marked *.

*