TCP Socket Programming in Node.js

Posted on October 26th, 2011 under Node.js
Tags: Clientnode.jsServerSocketTCP

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 HOST = '127.0.0.1';
var PORT = 6969; // Create a server instance, and chain the listen function to it
// The function passed to net.createServer() becomes the event handler for the 'connection' event
// The sock object the callback function receives UNIQUE for each connection
net.createServer(function(sock) {
    
    // We have a connection - a socket object is assigned to the connection automatically
    console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);
    
    // Add a 'data' event handler to this instance of socket
    sock.on('data', function(data) {
        
        console.log('DATA ' + sock.remoteAddress + ': ' + data);
        // Write the data back to the socket, the client will receive it as data from the server
        sock.write('You said "' + data + '"');
        
    });
    
    // Add a 'close' event handler to this instance of socket
    sock.on('close', function(data) {
        console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort);
    });
    
}).listen(PORT, HOST); console.log('Server listening on ' + HOST +':'+ PORT);

The same thing can be accomplished in a slightly different way. Make sure to include the necessary variables from the last example for this one to work.

var server = net.createServer();
server.listen(PORT, HOST);
console.log('Server listening on ' + server.address().address +':'+ server.address().port);
server.on('connection', function(sock) {
    
    console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);
    // other stuff is the same from here
    
});

So what's the difference? Basically they are the same thing, it's just we used different conventions of the JavaScript language. In the first example, we passed the connection event handler to net.createServer(), and chained the listen() function. In the latter, we took a more 'conventional' approach. Either way works.

Writing a TCP Client

Now let's write a client to connect to the server we created. The following code creates a simple client which connects to the server, sends a message to server, and disconnects after getting a response from the server. Read the comments to follow the code.

var net = require('net');

var HOST = '127.0.0.1';
var PORT = 6969; var client = new net.Socket();
client.connect(PORT, HOST, function() {     console.log('CONNECTED TO: ' + HOST + ':' + PORT);
    // Write a message to the socket as soon as the client is connected, the server will receive it as message from the client
    client.write('I am Chuck Norris!'); }); // Add a 'data' event handler for the client socket
// data is what the server sent to this socket
client.on('data', function(data) {
    
    console.log('DATA: ' + data);
    // Close the client socket completely
    client.destroy();
    
}); // Add a 'close' event handler for the client socket
client.on('close', function() {
    console.log('Connection closed');
});

So that's the very basics of TCP socket programming in Node.js, hope it helped you understand socket programming in Node better. Note that socket programming is a lot more than these simple examples. Once you start exchanging huge chunks of data and want to do complex things you will need to understand and use Streams and Buffers among other things.

Further Reading

  1. Node.js net Module
  2. Node.js Streams
  3. Node.js Buffers

TCP Socket Programming in Node.js的更多相关文章

  1. 基于Unix Socket的可靠Node.js HTTP代理实现(支持WebSocket协议)

    实现代理服务,最常见的便是代理服务器代理相应的协议体请求源站,并将响应从源站转发给客户端.而在本文的场景中,代理服务及源服务采用相同技术栈(Node.js),源服务是由代理服务fork出的业务服务(如 ...

  2. 一文搞懂如何使用Node.js进行TCP网络通信

    摘要: 网络是通信互联的基础,Node.js提供了net.http.dgram等模块,分别用来实现TCP.HTTP.UDP的通信,本文主要对使用Node.js的TCP通信部份进行实践记录. 本文分享自 ...

  3. 使用node.js 进行服务器端JavaScript编程

            node.js 入门        node.js 可以运行在 Linux.Windows 和 Macintosh 等主流的操作系统上.在 Windows 平台上运行 node.js ...

  4. node.js入门(二) 模块 事件驱动

    模块化结构 node.js 使用了 CommonJS 定义的模块系统.不同的功能组件被划分成不同的模块.应用可以根据自己的需要来选择使用合适的模块.每个模块都会暴露一些公共的方法或属性.模块使用者直接 ...

  5. 高并发下的Node.js与负载均衡

    新兴的Node.js已经吸引了很多开发人员的眼光,它提供给我们一个快速构建高性能的网络应用的平台.我也开始逐步投入node.js的怀抱,在学习和使用的过程中,遇到了一些问题,也有一些经验,我觉得有必要 ...

  6. [转]为什么我要用 Node.js? 案例逐一介绍

    原文地址:http://blog.jobbole.com/53736/ 介绍 JavaScript 高涨的人气带来了很多变化,以至于如今使用其进行网络开发的形式也变得截然不同了.就如同在浏览器中一样, ...

  7. 【特别推荐】Node.js 入门教程和学习资源汇总

    这篇文章与大家分享一批很有用的 Node.js 入门教程和学习资源.Node 是一个服务器端的 JavaScript 解释器,它将改变服务器应该如何工作的概念.它的目标是帮助程序员构建高度可伸缩的应用 ...

  8. 【转】为什么我要用 Node.js? 案例逐一介绍

    原文转自:http://blog.jobbole.com/53736/ 介绍 JavaScript 高涨的人气带来了很多变化,以至于如今使用其进行网络开发的形式也变得截然不同了.就如同在浏览器中一样, ...

  9. Node.js 入门教程和学习资源汇总

    这篇文章与大家分享一批很有用的 Node.js 入门教程和学习资源.Node 是一个服务器端的 JavaScript 解释器,它将改变服务器应该如何工作的概念.它的目标是帮助程序员构建高度可伸缩的应用 ...

随机推荐

  1. Mac 10.13安装telnet

    狗日的Mac 10.13默认不自带telnet!!!苹果你以为你的操作系统真的那么平民吗,别做梦,用你只不过是为了开发!!! 安装: brew install telnet 如果你用上述方法安装不上, ...

  2. 任务调度框架FluentScheduler简介

    之前我在文章中介绍过.net中的任务调度框架Hangfire,HangFire虽然本身输入比较简单好用的,但是,如果我们的程序本身提供的服务不是任务调度,而任务调度只是里面并不重要的小功能的时候,用H ...

  3. 【Go命令教程】2. go build

    go build 命令用于编译我们 指定的  源码文件 或 代码包 以及它们的依赖包. 例如,如果我们在执行 go build 命令时不后跟任何代码包,那么命令将试图编译当前目录所对应的代码包.例如, ...

  4. linux设置命令行启动

    做spark,内存大的话运行很快,否则运行很慢,主节点用界面,其他用命令行,然后scp,或者ssh 去其他主机最访问 1, 关闭图形界面: [root@bogon ~]# init 3   // 关闭 ...

  5. socket listen参数中的backlog

    服务器监听时,在每次处理一个客户端的连接时是需要一定时间的,这个时间非常的短(也许只有1ms 或者还不到),但这个时间还是存在的.而这个backlog 存在的意义就是:在这段时间里面除了第一个连接请求 ...

  6. poj1050最大子矩阵和

    这篇是看了别人的报告写的,就当是屡屡思路好了. 题目大意.给定一个n阶矩阵(方阵),每一个元素中存在一个数字.任务就是求出一个最大的子矩阵使得矩阵元素之间的和是最大的. n=100; 1.矩阵A[m] ...

  7. 前端使用AngularJS的$resource,后端ASP.NET Web API,实现分页、过滤

    在上一篇中实现了增删改查,本篇实现分页和过滤. 本系列包括: 1.前端使用AngularJS的$resource,后端ASP.NET Web API,实现增删改查2.前端使用AngularJS的$re ...

  8. 【C++】拷贝构造函数和赋值符函数

    在C++中,调用拷贝构造函数有三种情况: 1.一个对象作为函数参数,以值传递的方式传入函数体. 2.一个对象作为函数返回值,以值传递的方式从函数返回. 3.一个对象用于给另外一个对象进行初始化(复制初 ...

  9. mysql慢查询监控及sql优化

    在my.ini添加如下代码,即可查看那个sql语句执行慢了 log-slow-queries = d:/log/mysql-slow.log long_query_time = 1 打开日志 log ...

  10. 行尸走肉第一季/全集The Walking Dead迅雷下载

    本季The Walking Dead 1 第一季(2010)看点:<行尸走肉>讲述了警察瑞克在一次执法行动中因中弹负伤而不省人事,当他从昏迷中苏醒后却惊讶地发现,这个世界已然天翻地覆.周遭 ...