Node.js– Socket Programming with C# and Javascript


  Installing Node.js on Windows, Mac
  Thanks to Ryan Dahl’s presentations and materials, I have been able to follow along and learn a little about Node.js. I hope to show you what I learn as I learn it. The first step is get the latest version of Node installed.
Node.js Website https://nodejs.org
o31alsyz

  Using Node.js interactively
  Bring up a command prompt. Bring up a command prompt. v2gm3clg Type in node start the interpreter. nugjogqo Define a function. You can ignore the “undefined” message. anpet5bd You can now call the function, passing in “212.” pxfpmsav Notice we get “100” as the answer, since 212 Fahrenheit is 100 Celsius.

  Write Node.js scripts and running them
  You can request the process id very simply. cz4aghaf If you want A LOT of information, just type in “process.”  It is a lot of information. qjgs4yvc This will list a lot details about the process, including environment variables. Running Node.js Scripts Simply type in “node [node.js code file]” c:\> node simpleServer.js   image setTimeout.js
 setTimeout(function () { console.log(" world"); }, 2000);console.log("Hello"); 
The point is that there is no “sleep” in Node. You cannot halt execution. The setTimeout() lets you do things in the background. In the code above the word “Hello” shows up immediately and “World” shows up 2 seconds later. setInterval.js
 setInterval(function () { console.log(" world"); }, 2000);console.log("Hello"); 
ibdqzodd

  A simple HTTP Server – Demo
  The code below creates a very basic web server.         image The code below does the following:
Line 1 Brings in the code to write an http server
Line 3 createServer() gets called, passing in some code as the callback.
Line 5 Indicate that the web server return plain text
Line 6 Send “Hello World” back to the browser.
image Here is the output. Notice that on the left we execute simpleServer.js. On the right side we execute the code in simpleServer.js by navigating a browser to https://127.0.0.1:8000. Note the 8000, because that is the port we are listening on. image        Inspecting http headers with Fiddler Fiddler is an HTTP debugging proxy server application. It captures HTTP traffic and logs it for the user to review. Here is what to notice about the call we just made.
HTTP/1.1 The latest application-level protocol for distributed, collaborative, hypermedia information systems.
Connection: Keep-Alive Means that a persistent connection is maintained with the web server. Modern http means with one connection you can get multiple responses.
Transfer-encoding is chunked Means that a server to can maintain an HTTP persistent connection for dynamically generated content. We dont know how big the content will be.
           image 

  A Node.js TCP Server
  We just demonstrated http. The next section is learning about TCP. TCP is considered a very lightweight protocol, free of the overhead of http. Notice in the code below we require ‘net,’ not ‘http.’ Everything else should look somewhat familiar from before. But let’s be clear. TCP is a transport layer protocol and HTTP is an application layer protocol. HTTP (usually) operates over TCP, so whichever option you choose, it will still be operating over TCP. TCP sockets are more bandwidth efficient, since HTTP contains a whole bunch of extra data (the headers) that would likely not be needed. HTTP is not particularly suited to n-way chat servers. tcpServer.js       
var net = require('net'); var tcp_server = net.createServer(function(socket) { socket.write('hello\n');                   socket.end('world\n'); }); tcp_server.listen(8000);
Let’s write a C# program to read those TCP bytes (“Hello World”)
 static void Main(string[] args){    TcpClient tcpClient = new TcpClient();    tcpClient.Connect("127.0.0.1", 8000);    NetworkStream clientStream = tcpClient.GetStream();    byte[] message = new byte[4096];    int bytesRead;    bytesRead = 0;    try    {        // Read up to 4096 bytes        bytesRead = clientStream.Read(message, 0, 4096);    }    catch    {         /*a socket error has occured*/     }    //We have read the message.    ASCIIEncoding encoder = new ASCIIEncoding();    Console.WriteLine(encoder.GetString(message, 0, bytesRead));    tcpClient.Close();}               
Here is the TCP client reading and displaying the bytes. image

Download for Azure SDK