NODEJS Create a TCP server-king0222_ server other

Source: Internet
Author: User
Tags readable

1.NODEJS provides the net module to us, so we create the TCP server is very simple:

 Require (' net '). Createserver (function (socket) {
   //New Connection
   Socket.on (' Data ', function (data) {
     // Got data
   });
   Socket.on (' End ', function (data) {
     //connection closed
   });
   Socket.write (' Some string ');
 Listen ();

Through var server = require (' net '). Createserver (); This line of code we can get a reference to the TCP server object.

The server object has the following several listening events registered:

Listening,connection,close,error

The following example listens to several events in the declaration cycle of a TCP server:

var server = require (' net '). Createserver ();
 var port =;
 Server.on (' Listening ', function () {
   Console.log (' Server is listening on Port ', port;
 });
 Server.on (' Connection ', function (socket) {
   Console.log (' Server has a new connection ');
   Socket.end ();
   Server.close ();
 });
 Server.on (' Close ', function () {
   console.log (' Server's now closed ');
 };
 Server.on (' Error ', function (err) {
   Console.log (' Error occurred: ', err.message);
 });
 Server.listen (port);

Once the connection is established, a socket object is used as the parameter in the callback, and we can manipulate the socket object, which mentioned that the object of the TCP connection is a readable and writable stream. As a stream object, it is able to listen for events such as Data,end, and as a writable stream, has a write () method. Here's an example of listening to user input:

 var server = require (' net '). Createserver (function (socket) {
   console.log (' New Connection ');
   Socket.setencoding (' utf ');
   Socket.write ("hello! You can start typing. Type ' quit ' to exit.\n ');
   Socket.on (' Data ', function (data) {
     Console.log (' Got: ', data.tostring ())
     if (Data.trim (). toLowerCase () = = ' Quit ') {
       socket.write (' Bye bye! ');
       return Socket.end ();
     }
     Feedback back to the client
     socket.write (data);
   Socket.on (' End ', function () {
     console.log (' Client connection ended ');
   })
 . Listen ();

Because the socket object is also a readable stream, you can air his pause () and resume (), or you can output a writable stream directly using the pipe () method:

 var ws = Require (' FS '). Createwritestream (' Helloworld.txt ');
 Require (' net '). Createserver (function (socket) {
   socket.pipe (WS);
 }). Listen ();

The code above creates a writable stream object and then outputs the writable stream object to the client. You can get a file named Helloworld.txt on the client,

You can use "telnet localhost 4001" to test this example.

Because the socket object has both the properties of a readable stream and the nature of the writable flow, the above example can be used in turn to form the following code:

 Require (' net '). Createserver (function (socket) {
   var rs = require (' FS '). Createreadstream (' Hello.txt ');
   Rs.pipe (socket);
 Listen ();

The above code outputs the contents of the Hello.text file to the client in the socket object, when the content output is complete, the TCP connection exits, as mentioned in the previous article, and the End method is executed by default when the data is read, so if you do not want this effect and stay connected, you can pipe the Pipe, add the second parameter: {end:false}, and rewrite end listening.

2. Idle socket when there are idle sockets appear when we need to do the corresponding cleanup work, by the SetTimeout method can help us to the idle socket object closed.

 var timeout =; Minute
 socket.settimeout (timeout);
 Socket.on (' timeout ', function () {
   socket.write (' Idle timeout, disconnecting, bye! ');
   Socket.end ();
 });

Here's a more concise way to use it:

 Socket.settimeout (60000, function () {
   socket.end (' Idle timeout, disconnecting, bye! ');
 });

3. Stay Connected

Copy Code code as follows:

Socket.setkeepalive (TRUE);

You can also add a second parameter to set the delay length:

Copy Code code as follows:

Socket.setkeepalive (True, 10000); Ten seconds

4. Whether to use the delay

Kernel will cache data before sending TCP packets, so it will occupy a certain latency, which is useful for some small packet scenarios, but if you do not want to have such a delay then you can set this:

Copy Code code as follows:

Socket.setnodelay (TRUE);

var port =;
var host = ' ... ';
Server.listen (port, host);

The second parameter of the Listen method is to listen for the IP address of the client and, if it is filled in, only listen for the IP that is filled in, otherwise it will listen for all IP addresses and will not be filled out by default. To shut down the server connection, we can use the Close method, and we can also listen to the event.

Copy Code code as follows:

Server.close ();
Server.on (' Close ', function () {
Console.log (' Server closed! ');
});

6. Create a simple TCP chat room server

var net = require (' net ');
 var server = Net.createserver ();
 var sockets = [];
 Server.on (' Connection ', function (socket) {
   Console.log (' Got a new Connection ');
   Sockets.push (socket);
   Console.log (' Sockets length: ', sockets.length);
   Socket.on (' Data ', function (data) {
     Console.log (' Got data: ', data.tostring ());
     Sockets.foreach (function (othersocket) {
       if (othersocket!== socket) {
         othersocket.write (data);
       }
     });
   });
   Socket.on (' Close ', function () {
     console.log (' connection closed ');
     var index = sockets.indexof (socket);
     Sockets.splice (index,);
     Console.log (' Sockets length: ', sockets.length);
   });
 Server.on (' Error ', function (err) {
   console.log (' Server error: ', err.message);
 });
 Server.on (' Close ', function () {
   console.log (' Server closed ');
 });
 Server.listen ();

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.