zoukankan      html  css  js  c++  java
  • TCP Socket Programming in Node.js

    TCP Socket Programming 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 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
  • 相关阅读:
    .net日期类与UNIX时间戳的相互转换,长数字
    钉钉的生日模块在哪
    js判断手机是苹果(IOS)还是安卓(android) H5手机端自适应宽高
    .net网站部署winserver2008R2 IIS只列出目录 浏览只显示目录浏览
    ajax有时请求不到数据 后台,有时收不到返回值的解决办法
    overflow不超出时不显示滚动条 属性解决内容未超出依然显示滚动条轨道的问题
    PB取datawindow生成的语句。要在datawindow的sqlpreview事件
    电脑C盘缓存路径在哪,清理C盘哪个文件夹可以删
    PB里执行写SQL语句
    SQL SERVER合并行。将多行数据合并成一行,字符串拼接
  • 原文地址:https://www.cnblogs.com/oxspirt/p/10339111.html
Copyright © 2011-2022 走看看