nodejs--Network Programming module

Source: Internet
Author: User
Tags server port

NET module provides an asynchronous network wrapper for TCP network programming, which contains methods for creating servers and clients. The Dgram module is designed for UDP network programming.

Reference link: https://nodejs.org/api/net.html, https://nodejs.org/api/dgram.html

One, the TCP Server

NET module creates a TCP server through the Net.createserver method and creates a client to connect to the server through the Net.connect method.

1. Create a TCP Server through the net module
//Server.jsvarNET = require (' net ');//Create a TCP servervarServer = Net.createserver (function(socket) {Console.log (' Client Connected '); //listening to client dataSocket.on (' Data ',function(data) {Console.log (' Server got data from client: ', data.tostring ());    }); //Listening for client disconnect eventsSocket.on (' End ',function(data) {Console.log (' Connection closed ');    }); //sending data to the clientSocket.write (' hello\r\n ');});//Start the serviceServer.listen (8080,function() {Console.log (' Server bound ');});
2. Create a client
//Client.jsvarNET = require (' net ');//connecting to a servervarClient = Net.connect ({port:8080},function() {Console.log (' Connected to server '); Client.write (' World!\r\n ');});//receiving data from the service sideClient.on (' Data ',function(data) {Console.log (' Client got data from server: ', data.tostring ()); //Disconnect Connectionclient.end ();});//Disconnect ConnectionClient.on (' End ',function() {Console.log (' Disconnected from server ');});

Running the TCP server code at one terminal, and the other terminal running the TCP client code, the results are as follows:

Second, simple chat room server 1, simple chat room service side

The first is to create a TCP server, and then to receive client connection requests, to obtain data sent by the client, to allow multiple clients to connect at the same time, so that all user connections need to be received, and the server broadcasts the data and forwards the data from the client to all other clients. Finally, the client that closes the connection is removed from the server broadcast list.

//Chatserver.jsvar net = require (' net ');//First step to create a TCP servervar server = Net.createserver ();//Store all client sockets//Fourth step, the server receives all user connections
var sockets = [];
///second step to receive client request Server.on ( ' connection ', function (socket) { console.log ( ' Got A new connection '); //Fifth step, server broadcast data Sockets.push (socket); ///step three, get the data sent by the client . Socket.on (   ' data ', function (data) { console.log ( ' Got data: ' , data); Sockets.foreach ( function (othersocket) {if (Othersoecket!== socket) {othersocket.write (data); } }); ]); //Sixth step, close the connection client to remove Socket.on from the Server broadcast list (' Close ', function () {Console.log (' A client connection closed '); var index = sockets.indexof (socket); Sockets.splice (index, 1); }); }); Server.on ( ' ERROR ', function (err) {console.log (' Server error: ', err.message);}); Server.on (' Close ', function () {Console.log (' Server closed ');}); Server.listen (8080);
2. The simple chat room client interprets the process module first

The process module is a global module of node. js that can be used directly anywhere without the introduction of the Require method. The process module allows you to obtain or modify settings for the current node. JS process.

The Process.stdin is used to obtain a readable stream from a standard input (readable stream).

Client code
//Chatclient.jsvarNET = require (' net ');p rocess.stdin.resume ();p rocess.stdin.setEncoding (' UTF8 ');varClient = Net.connect ({port:8080},function() {Console.log (' Connected to server '); //gets the input stringConsole.log (' Input: '); Process.stdin.on (' Data ',function(data) {//send the input string to the serverConsole.log (' Input: ');        Client.write (data); //close connection when entering ' close ' string        if(data = = ' close\n ')) {client.end (); }    });});//get the data sent over the serverClient.on (' Data ',function(data) {Console.log (' Other user\ ' input ', data.tostring ());}); Client.on (' End ',function() {Console.log (' Disconnected from server '); //exiting the client programprocess.exit ();});

A terminal window executes $ node chatserver.js running the server code.

The other two terminal Windows Execute $ node chatclient.js to run the client code.

The results are as follows:


Third, UDP programming

UDP creates a service through Dgram.createsocket.

1. Server-side code
//Udpserver.jsvarDgram = require ("Dgram");varServer = Dgram.createsocket ("UDP4"); Server.on ("Error",function(Err) {Console.log ("Server error:\n" +err.stack); Server.close ();});//receiving messages from the clientServer.on ("message",function(msg, rinfo) {Console.log ("Server got:" + msg.tostring () + "from" + Rinfo.address + ":" +rinfo.port);});//Monitoring ServicesServer.on ("Listening",function() {    varAddress =server.address (); Console.log ("Server listening on" + Address.address + ":" +address.port);}); Server.bind (41234);//Server Listening 0.0.0.0:41234
2, the Client

The sending message must be created through buffer.

// Udpclient.js var dgram = require (' Dgram '); var client = Dgram.createsocket (' udp4 '); var New Buffer (' Hello Shiyanlou 'function(err, bytes) {    client.close ();});

The operation results are as follows

Four, the wrong row

1, Error:connect econnrefused 127.0.0.1:8080

The server port is not open.

The author starof, because the knowledge itself in the change, the author is also constantly learning and growth, the content of the article is not updated regularly, in order to avoid misleading readers, convenient tracing, please reprint annotated source: http://www.cnblogs.com/starof/p/5056519. HTML has a problem welcome to discuss with me, common progress.

nodejs--Network Programming module

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.