Posts

Showing posts from October, 2012

How to implement a real-time chat server in PHP using Server-Sent Events (update: added C benchmark)

Lessons learned: A web server written in PHP can give more than 10000 req/s on small hardware A web server written in PHP is not slower than being written in Java (without threads) A web server written in PHP is 30 percent slower than being written in C (without threads) Realtime applications can be developed in PHP without problems PHP normally runs inside a web server like Apache or nginx. This keeps all requests separate from each other and does not allow sharing memory or connections. To implement a chat server, the browser has to poll the server regularly for new data. The data is stored in a database and looked up for each request. This is very slow, takes a lot of resources on the server and does not give messages in realtime. Newer browsers support data being pushed from the server to the client. There are two techniques used: WebSockets (full-duplex) and Server-Sent Events (push notifications) Using these techniques, one connection stays open for each client and the server...

How to write JavaScript in MVC style

Image
Intent ============================================================================== This tutorial explains a way to implement MVC (Model View Controller) pattern in client script using pure JavaScript . Idea is to highlight basic fundamentals of implementing MVC in client code. If you grab these basics, you can easily create advance implementations with lesser code using various libraries like JQuery and Knockout etc. Quick brush up on MVC Instead of getting theoretical, I'll put it this way: View : These are the HTML elements in your UI - TextBoxes, HiddenBoxes, Images, Tables etc. For example, in Google home page, view elements includes Search TextBox, Search Button, Search result div container, Suggestions display div container etc. Model :  Model represents data which drives functionality of screen. It may or may not have 1:1 mapping with your view elements. For example, in Google search page, model may contain an array of autoSuggest words or an array of search results...

How to write JavaScript functions in different styles

INTENT ================================================================= This article is to explore different ways to write JavaScript functions. All example below are in context of plain JavaScript and do not depend on any library like JQuery (which might come as a surprise to few :) Level: Beginners Original Basic implementation.. Declare a method and call at some point later function SayHello(msg) { alert(msg); } //call explicitly SayHello('my name is'); //alerts "my name is" Different style where function is assigned to a variable and then called later var SayHello = function(name) { alert(name); }; SayHello('Deepak'); NOTE: Check the ; at end of function (i.e. after }) . This was not required in previous example because we declared a method. However, now we are assigning a function to a variable just like we say var i = 10; If you miss this ';', function would still execute properly but many IDE's may complain th...

Convert Debian amd64 to multi-arch

Do following steps... sudo dpkg --add-architecture i386 sudo sed -i 's/deb\ /deb\ [arch=amd64,i386]\ /g' /etc/apt/sources.list sudo apt-get clean; sudo apt-get autoclean; sudo apt-get update After that you can install the packages that only support i386 such like skype. Enjoy it!

PHP Framework Comparison (update: opcode caching)

Image
Reading about PHP frameworks, you'll get a lot about Symfony and Zend Framework. It is true that these frameworks have a lot of features and do great marketing. But what about performance and scalability? There are 2 kinds of frameworks: those written in C as an extension and those written in PHP Using a framework written in C will definitively give the best performance. But fixing (security) bugs and maintaining them requires C knowledge. If the documentation is not complete or incorrect, you might need to read the code to understand the functionality or wait for the maintainer to help you. So if you don't need super high performance, my recommendation is using a framework written in PHP. Here is a test from Laruence (PHP core developer): higher numbers are better, source Here is another test from Zeev Suraski (Zend/PHP core developer): higher numbers are better, source Here is another excellent test from Wang Rui: smaller numbers are better, source (with call graphs, respon...

Conditionally render MVC layout section

Error: The following sections have been defined but have not been rendered for the layout page "~/_SiteLayout.cshtml" Reason: Let's say there is a Layout as following: <html> <head> </head> <body> @RenderBody() @RenderSection("footer") </body> </html> And a view as following: <H1>Hello World</H1> @section footer{ Copyright 2012 } When rendered, <h1>Hello World</h1> will be rendered by RenderBody() while Copyright 2012 will be rendered by RenderSection(). But, what if for some reason you want to display footer conditionally on Layout? So for that, if you do something like following, you will encounter an error: <body> @RenderBody() if(condition){ @RenderSection("footer") } </body> Reason is that MVC needs to flush out section declared in your view. Else it displays error as on top of article. To resolve this, there is a quick trick: <body> @RenderBody() if(condition...

Restart networking service on Debian

Most Debian user should run into this problem before they find out a good way to restart networking service. Debian deprecated the restart option of /etc/init.d/networking script for security issue. Users will get following warning when they do restart: Running /etc/init.d/networking restart is deprecated because it may not enable again some interfaces ... (warning). And their network won't be restart finally. How to restart the networking service? There are several ways to achieve that. (Login as root or sudo it) /etc/init.d/networking stop && /etc/init.d/networking start (You'd better run the command on console than remote it) inovke-rc.d networking restart Hope those helpful for you and me. :-)

PHP do-while loop

In the PHP while loop if the initial condition is false then it will not execute the inner code but in real life application sometimes we need to execute the inner code at least one time even the condition is false. To do this PHP provides do-while loop . So the general form of PHP do-while loop is do{  //The body    }while(condition); In each time the do-while loop first executes the body of the loop and then evaluates the condition. If the condition returns true then the loop will repeat otherwise the loop terminates. PHP do-while example Now take a look at an example based on PHP do-while condition. <?php $value=1; do {     echo $value;     $value++;     }while(!$value==1); ?>  In this code snippet at first it prints the value 1 though the condition is not true. After printing 1 then it checks the while condition. Now the while condition is false so that the loop will be terminated. Consider another example where...

PHP while loop

PHP while is an iterative loop by which we can repeat a condition based on condition. The general form of PHP while loop is while(condition) { executed satement } PHP while loop starts with the name while and then condition. If the condition is true then it allows to execute the statement otherwise it terminates the while loop. So we can say that the condition part returns true or false. PHP while loop example Now we try to do a problem using php while loop. The problem is to add 1,2,3,4,5,6,7,8,9 and 10. So the code is <?php $value=1; $sum=0; while($value<=10) {     $sum=$sum+$value;     $value++;     }     echo $sum; ?> If the while condition is not true then the PHP while loop will not execute the inner code. Here is an example. <?php $value=1; $sum=0; while(!$value==1) {     $sum=$sum+$value;     $value++;     }     echo $sum; ?>

Coding Puzzle#1 - Generic Random Status Filler

Level: Intermediate-Advance Topic : Plain Loops Who Wins : One who accomplishes this task with least number of iterations Short Description : Create a method such that it is capable of populating enum property all objects in a list with random values based on pre-defined ratio Puzzle Details: Let’s say I’ve a following enum and a class: public enum TASK_STATUS     {         ToBeStarted,         InProgress,         Completed     }     public class TodoTask     {         public int Id { get ; set ; }         public string Comment { get ; set ; }         public TASK_STATUS Status { get ; set ; }     } I want to create 50  TodoTask fake instances and add it to a list List < TodoTask >() . How...