"NodeJs" A simple instance of sending and receiving data using TCP sockets

Source: Internet
Author: User

Because the TCP protocol is a streaming protocol, there is a problem with sticky packets when sending and receiving data. This example solves the problem of sticky packets by using a custom SPTCP packet protocol to encapsulate TCP data once again.

Note: Its performance remains to be optimized. Optimization direction: Use TCP's own receive window cache.

    • Sptcp.js
/** * script:sptcp.js * Description: Simple packet Protocol SPTCP class * authors: [email protected] * date:2016-04-14 */var util = Requi Re (' util '); function sptcp (socket) {//Resolution at the stage var _sp_parse_step = Sptcp.sp_parse_step.    HEADER;    Receive cache var _sp_rcv_buf = new Buffer (0);    Baotou var _sp_header = null;    Package body var _sp_body = null;    Socket this.socket = socket; Parsing the whole package method function _spparsesppacket (func) {if (_sp_rcv_buf.length >= sptcp.sp_header_length) {//parsing            Baotou _sp_header = {bodylength: _sp_rcv_buf.readuint16le (0, True)};            Crop Receive Cache _sp_rcv_buf = _sp_rcv_buf.slice (sptcp.sp_header_length); Resolves the package body _sp_parse_step = Sptcp.sp_parse_step.            BODY;        _spparsebody (func);    }    }; Parsing the package Body method function _spparsebody (func) {if (_sp_rcv_buf.length >= _sp_header.bodylength) {var Packe            t = _sp_rcv_buf.tostring (' UTF8 ', 0, _sp_header.bodylength); Util.log (' [' +socket.remoteaddress+ ']->[' +socket.localaddress+ '] receive: ' +packet ';            Crop Receive Cache _sp_rcv_buf = _sp_rcv_buf.slice (_sp_header.bodylength);                Process message try {var msg = json.parse (packet);            Func (msg);            } catch (E) {util.log (e);            }//Empty header and package body _sp_header = null;            _sp_body = null; Resolves the next package _sp_parse_step = Sptcp.sp_parse_step.            HEADER;        _spparsesppacket (func);    }    };        Receive Data This.spreceivedata = (data, func) = {if (!func) func = msg + undefined;        Merge old and new data _sp_rcv_buf = Buffer.concat ([_sp_rcv_buf, data]); Parse processing data if (_sp_parse_step = = Sptcp.sp_parse_step.        HEADER) {_spparsesppacket (func); } else if (_sp_parse_step = = Sptcp.sp_parse_step.        BODY) {_spparsebody (func);    }    }; Send data This.spsenddata = msg + = {var packet = json.stringify (msg);       var body_buf = new Buffer (packet);        var head_buf = new Buffer (sptcp.sp_header_length);        Head_buf.writeuint16le (body_buf.length);        var snd_buf = Buffer.concat ([Head_buf, Body_buf]);    This.socket.write (SND_BUF);    };    Destruction Method This.spdestroy = () = = {Delete This.socket; };} Header length, unit byte Sptcp.sp_header_length = 4;//resolution at the stage Sptcp.sp_parse_step = {header:0,//parsing header phase Body:1,//parsing the package phase};ex Ports. Sptcp = sptcp;
    •  spsvr.js
/** * script:spsvr.js * DESCRIPTION:SPTCP Server side * Authors: [email protected] * date:2016-04-15 */var util = require ( ' util '); var net = require (' net '); var sptcp = require ('./sptcp ').    Sptcp;var Server = net.createserver (client = {Util.log (' Client connected: ' + client.remoteaddress);    Socket inheritance sptcp sptcp.call (client, client); Listen to the Data event Client.on (' data ', data = {client.spreceivedata (data, msg = + {Util.log (' susl msg:            ' + util.inspect (msg));        Client.spsenddata (msg);    });    });        Listener End Event Client.on (' End ', () = {Util.log (' Disconnected from client: ' + client.remoteaddress);    Client.spdestroy ();    });        Listen for Error event Client.on (' error ', err = {Util.log (err);    Client.end (); });}); var listen_options = {host: ' 172.16.200.26 ', Port:6200,};util.log (' Listen options: ' + util.inspect (listen_options ); Server.listen (listen_options, () = {Util.log (' server Bound ');});
    •  spcli.js
/** * Script:spcli.js * DESCRIPTION:SPTCP Client * Authors: [email protected] * date:2016-04-15 */var util = require (' Util '), var net = require (' net '), var sptcp = require ('./sptcp ').  Sptcp;var connect_options = {host: ' 172.16.200.26 ', port:6200, Localport:6201,};util.log (' Connect options: ' + Util.inspect (connect_options)); var client = Net.connect (Connect_options, () =>{//Socket Inheritance sptcp sptcp.call (client, C    Lient); Listen to the Data event Client.on (' data ', data = {client.spreceivedata (data, msg = + {Util.log (' susl msg:        ' + util.inspect (msg));    });    });        Listener End Event Client.on (' End ', () = {Util.log (' Disconnected from server: ' + client.remoteaddress);    Client.spdestroy ();    });        Listen for Error event Client.on (' error ', err = {Util.log (err);    Client.end ();    });        Send Message for (var i=0; i<10; i++) {var msg = {op: ' Test ', msg: ' Hello, grass millet! ', times:i};    Client.spsenddata (msg); }//Close connection CLIEnt.end ();}); 

NodeJs A simple instance of sending and receiving data using a TCP socket

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.