joydip_kanjilal
Contributor

Developing applications with Node.js and C#

opinion
May 05, 20155 mins
Software Development

Take advantage of Node.js to build fast and scalable server side applications using JavaScript

Node.js is an open source, cross-platform runtime environment for building server side and networking applications using JavaScript. Node.js provides an asynchronous, event driven framework to build highly scalable networking applications using JavaScript. And, yes — Node.js leverages all the benefits that an open source technology has to offer. You can take advantage of the package manager called npm for publishing and sharing open source Node.js libraries with the Node.js community. This article presents a discussion on the concepts of Node.js, why it is needed and illustrates the concepts covered by implementing a simple TCP Server. This TCP Server is consumed using a console application written in C#.

What is Node.js?

Node.js operates on a single thread and leverages the power of asynchronous programming to provide support for many concurrent connections sans the overhead cost of thread switching. Node.js applications are written using JavaScript and can be executed on a wide variety of platforms that include: OS X, Microsoft Windows, Linux, FreeBSD, NonStop and IBM i. Node.js was invented in 2009 by Ryan Dahl and is built on top of the Google V8 JavaScript engine and provides a non-blocking event driven architecture.

You can take advantage of Node.js to build fast and highly scalable servers in JavaScript sans the need of multi-threading. The official website of Node.js states: “Node.js is a platform built on Chrome’s JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.”

The reason Node.js is built on top of this engine is that V8 is open source and fast. You can learn more on this engine from this site.

Getting started

First things first, you should install Node.js to build applications that leverage Node.js library. You can get the installer for Node.js from the official website. You can also go through the manual and documentation on Node.js there — it is detailed and includes code snippets wherever applicable.

Implementing an HTTP server in Node.js

In this section we will discuss how we can build our first Node.js application and get it up and running. If you would like to build a simple HTTP Server you can just write the following code in a JavaScript file, save it with a name and you are good to go!

var http = require("http"); http.createServer(function(request, response) { response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Server started..."); response.end(); }).listen(9000);

Refer to the code snippet given above. The first statement includes the http module so that you can create a Http Server. The Http Server is created using the createServer() method and it listens for incoming connections at port 9000. When this code is executed, the Http Server starts and the message “Server started…” is display in the console.

To execute the script and get the server started, you need to invoke the script from the console using the following statement. node IDGServer.js

Modules in Node.js

Node.js includes a collection of modules. Modules encapsulate a collection of related functions into one single unit. You can also export modules if you need to. The modules in Node.js provide a simple and easy to use API that can be used for File I/O, Networking (using HTTP, TCP, UDP, etc protocols), extend the Node.js library and implement Cryptography functions, etc. The following code snippet illustrates how you can export a module to make it available to other script files.

var exports = module.exports = {};

To import a module, you need to use the “require” keyword as shown below.

var moduleObj = require("./IDGCore.js");

You can know more on how you can create modules and import or export them as and when needed from this article. http://www.sitepoint.com/understanding-module-exports-exports-node-js/

Implementing a TCP server in Node.js

Let’s now build a simple TCP server using Node.js and consume it using C#. To build a simple TCP Server in Node.js here’s all the code you would need to write. Create a file called IDGServer.js and copy the following code into it.

<code>var net = require(‘net’); var tcp_server = net.createServer(function(socket) { socket.write('Joydipn'); socket.end('Kanjilaln'); }); tcp_server.listen(8000);

You can execute the script and run the TCP Server using the following statement in the console.

<code>node IDGServer.js

The following piece of C# code can be used to read from the TCP socket we just created and display the text on the console.

<code>public static void ReadData() { TcpClient tcpClient = new TcpClient(); tcpClient.Connect("127.0.0.1", 8000); NetworkStream clientStream = tcpClient.GetStream(); byte[] data = new byte[4096]; int bytesRead = 0; try { bytesRead = clientStream.Read(data, 0, 4096); ASCIIEncoding encoder = new ASCIIEncoding(); Console.WriteLine(encoder.GetString(data, 0, bytesRead)); } catch(Exception ex) { //Process the error, write to logs, etc. } finally { tcpClient.Close(); } }

In my future posts here I would explore more on Node.js and show how you can use Node.js in enterprise applications.

joydip_kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author