Posts

Showing posts from April, 2019

Week 11 - Programming TCP Sockets in Node.js

Programming TCP Sockets in Node.js Eager to know how sockets are programmed in Node? There are three variants of sockets in Node - i. TCP, ii. UDP, iii. UNIX domain. In this particular post, I will show you the basics of TCP socket programming in Node.js. There are two categories of TCP socket programs you can write - i. server, ii. client. A TCP server listens for connections to it from clients and send data to the client. A TCP client connects to a TCP server exchange data with it. The communication between client and server happens via sockets. Programming TCP sockets in Node requires the  net  module, which is an asynchronous wrapper for network programming. The  net  module is capable of many things, but for today we'll just focus on creating a TCP server and a client. Writing a TCP Server Here is an example of a very simple TCP server written in Node. Read the comments thoroughly, it explains how the code works. var net = require ( 'net' ); var HOS

Week 10 - Programming UDP Sockets in Node.js

For all things UDP in Node.js, you will need to use the  dgram  library, so read it up well and good. UDP Server Here is a simple example of a UDP server. var PORT = 33333 ; var HOST = '127.0.0.1' ; var dgram = require ( 'dgram' ); var server = dgram . createSocket ( 'udp4' ); server . on ( 'listening' , function () {      var address = server . address ();     console . log ( 'UDP Server listening on ' + address . address + ":" + address . port ); }); server . on ( 'message' , function ( message , remote ) {     console . log ( remote . address + ':' + remote . port + ' - ' + message ); }); server . bind ( PORT , HOST ); Things to Note HOST is optional in  server.bind() . If omitted, it will be listening on  0.0.0.0 , which might be what you want in some cases. The  message  event is fired, when a UDP packet arrives destined for this server. The  listeni