Using TCP sockets in Node.js to program __ Applet

Source: Internet
Author: User

Turn from: http://cnodejs.org/topic/4fb1c1fd1975fe1e1310490b

using TCP socket programming in Node.js

Translated from http://www.hacksparrow.com/tcp-socket-programming-in-node-js.html

Want to know how to use socket programming in Nodejs. There are three kinds of socket:1 in the Nodejs. tcp,2. udp,3. UNIX domain sockets, this article mainly introduces TCP's BASIC programming knowledge in Nodejs.

You can create two types of TCP sockets: 1. Service side, 2. Client. Server-side TCP listens for connection requests from the client and sends data to the client using a TCP connection, and client TCP connects to the service side and interacts with the data. A two-way communication between the client and the server relies on sockets.

Using TCP in NODEJS requires referencing net modules. NET module is the encapsulation of asynchronous network programming in Nodejs, can do a lot of things, this article focuses only on how to use this module to create a server-side TCP socket with the client.

Creating a TCP service side

The following is a simple example of creating a TCP service socket in Nodejs, as described in the code comment.

var net = require (' net ');

var HOST = ' 127.0.0.1 ';
var PORT = 6969;

Create a TCP server instance, call the Listen function to start listening for the callback function of the specified port
//Incoming net.createserver () as the handler for the "Connection" event
//In every "connection" event, the callback function receives the socket object that is the only
net.createserver (function (sock) {

    //We get a connection-the connection automatically associates a socket object
    Console.log (' CONNECTED: ' +
        sock.remoteaddress + ': ' + sock.remoteport ');

    Add a "Data" event handler function for this socket instance
    sock.on (' Data ', function (data) {
        console.log (' data ' + sock.remoteaddress + ') : ' + data ';
        When the data is sent back, the client will receive the data from the server
        sock.write (' you said ' + Data + ');
    });

    Add a "Close" event handler for this instance of the socket
    Sock.on (' Close ', function (data) {
        console.log (' CLOSED: ' +
            Sock.remoteaddress + "+ sock.remoteport);
    })

. Listen (PORT, HOST);

Console.log (' Server listening on ' + HOST + ': ' + PORT ');

The server side can also accept TCP connections in a slightly different way, that is, explicitly handling the "connection" event:

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 content is the same as the preceding precedent

});

The above two examples are written in different ways, and there is no essential difference.

Creating a TCP client

Now let's create a TCP client to connect to the server that you just created, which sends a string of messages to the server and closes the connection after receiving feedback from the server. The following code describes the process.

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);
    Send the data to the server immediately after the connection is established, and the server will receive these data 
    client.write (' I am Chuck norris! ');

Adding the "Data" event handler
//data to the client is the Client.on of the server's postback
(' data ', function (data) {

    console.log (' data: ' + data ');
    //completely shut down connection
    Client.destroy ();

});

Add the "Close" event handler function to the client
Client.on (' Close ', function () {
    console.log (' Connection closed ');
});

This is the basic process of TCP network programming in Nodejs, hoping to be helpful to you. Note that socket programming is much more complex than the example here, when you use sockets to send large amounts of data or complete complex tasks, you will use the flow (Streams) and buffer (buffers) and other related modules.

Further reading <ol> nodejs net module Nodejs Stream module Nodejs buffer module </ol>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.