Getting Started with node. JS Development-SOCKET (socket) programming

Source: Internet
Author: User
Tags socket error

node. JS's net module provides a socket programming interface that allows us to implement application protocols using a lower-level socket interface. This time we look at a simple echo server example, including the service side and the client code.

Sockets can also be programmed using JavaScript, haha, this acid is cool!

Code

Two parts of the server and the client.

Echoserver Code Analysis

Echoserver.js:

var net = require("net");// server is an instance of net.Server// sock is an instance of net.Socketvar server = net.createServer(function(sock){  console.log(‘client connected, address -  ‘, sock.remoteAddress, ‘ port - ‘, sock.remotePort);  sock.setEncoding(‘utf8‘);  sock.on(‘data‘, function(data){    console.log(‘got data from client - ‘, data);    sock.write(data);  });  sock.on(‘end‘, function(){    console.log(‘client disconnected‘);  });  sock.on(‘error‘, function(err){    console.log(‘socket error - ‘, err);  });});server.maxConnections = 10;server.listen(7, function(){  console.log(‘echo server bound at port - 7‘);});

NET Module API is here: https://nodejs.org/api/net.html.

I use Net.createserver to create a server instance, the return value of this method is a Net.server instance, Net.server provides a listen method, let us listen to a port to accept the client connection, but also provides some properties, such as Maxconnectio NS can set the maximum number of concurrent connections to the server (when the number of connections to the server exceeds this value, subsequent connections will be rejected), and others, see the document: Https://nodejs.org/api/net.html#net_class_net_server.

Net. The server also provides events such as error, connection, and so on. When a client connection is accepted, the connection event is emitted and the event takes a net. The socket object is used as a parameter to access this net in the callback function. Socket instance to interact with the client. In my code, I passed a callback to the Createserver method to handle the connection event, and I can actually modify it slightly to handle the client connection by listening to the connection event. The new code is as follows:

var net = require("net");var server = net.createServer();server.on(‘connection‘, function(sock){  console.log(‘client connected, address -  ‘, sock.remoteAddress, ‘ port - ‘, sock.remotePort);  sock.setEncoding(‘utf8‘);  sock.on(‘data‘, function(data){    console.log(‘got data from client - ‘, data);    sock.write(data);  });  sock.on(‘end‘, function(){    console.log(‘client disconnected‘);  });  sock.on(‘error‘, function(err){    console.log(‘socket error - ‘, err);  });});server.maxConnections = 10;server.listen(7, function(){  console.log(‘echo server bound at port - 7‘);});

The effect is the same.

Net. The socket object has some methods, such as write, which writes data. There are also some events, such as error, end, data, and so on, see the code to understand the usage. There are some properties, such as Remoteaddress, RemotePort.

I processed the data event, which has a parameter that represents the read. I use net directly in the callback. Socket.write sends the data back to the client intact. This is an implementation of ECHO. There is also a more convenient implementation, which is called net. Socket pipe method, the node. JS NET module documentation provided in the echoserver is used pipe, to see it.

Echoclient Code Analysis

Echoclient.js:

  var net = require ("NET"), var readline = require (' ReadLine '); Console.log (' type ' "Exit" or "quit" to quit. '); /sock is an instance of net.  Socketvar sock = Net.connect ({port:7}, function () {console.log (' server Connected ');  Sock.setencoding (' UTF8 '); Sock.write (' Hello Echo server\r\n ');}); Sock.on (' Data ', function (data) {Console.log (' Got data from server-', data);}); Sock.on (' End ', function () {Console.log (' client disconnected ');}); Sock.on (' Error ', function (err) {Console.log (' socket error-', err);});  Sock.on (' Close ', function () {Console.log (' echo client was closed '); Process.exit (0);});  var RL = Readline.createinterface ({Input:process.stdin}), function Quitecho () {rl.close ();  Sock.end (); Console.log (' Quit Echo client ');}  Rl.on (' line ', function (cmd) {if (Cmd.indexof (' quit ') = = 0 | | cmd.indexof (' exit ') = = 0) {Quitecho ();  }else{sock.write (cmd + ' \ r \ n '); }}); Rl.on (' SIGINT ', Quitecho);  

The client code is a little bit longer. Because I wanted echo to be more like Echo, I called the ReadLine module to read the data from the standard input and send it to the client. ReadLine's documentation is here: https://nodejs.org/api/readline.html. Like its name, ReadLine allows you to read a stream in a row. It is more common to read the standard input stream. ReadLine has some events, we use the "line" event, when a row of data is ready to be emitted, with a parameter representing the data. I listen to the line event and call net in the callback. The write method of the socket writes the data. When you enter "quit" or "exit" in the console, call Quitecho to exit.

The Net.connect method can be connected to the specified server, and its prototype is as follows:

net.connect(options[, connectionListener])

The first parameter is object, which is used to specify and connect related options, such as host, port, etc. on the server side, and localhost is used as the server host name by default if host is not specified. I only specified the port in the example.

Net.connect returns the Net.socket object, once the socket instance is taken, you can use Net.socket to do whatever you want. I listened to the data event to receive the server-side information and listened to the close event to exit the process. Net. The specific API for the socket, refer to Https://nodejs.org/api/net.html#net_class_net_socket.

Run the sample

Storytelling in a word, then clapped, ah ha, can run. By executing "node Echoserver.js" and then "Node Echoclient.js", you can enter some content in the Echoclient console interface. Effects such as:

Other articles:

    • node. JS Development Primer--notepad++ for node. js
    • Get started with node. JS-Use dialog box Ngdialog
    • Introduction to node. JS Development--Introducing Uibootstrap
    • Get started with node. JS-Transform Logindemo with MongoDB
    • node. JS Development Primer--mongodb and Mongoose
    • Get started with node. JS Development-Use cookies to stay signed in
    • Getting Started with node. JS-Using ANGULARJS built-in services
    • node. JS Development Primer--angular Simple Example
    • Introduction to node. JS Development-Using ANGULARJS
    • Getting Started with node. JS Development-Using the Jade template engine
    • node. JS Development Starter--express Routing and middleware
    • node. JS Development Primer--express Installation and use
    • node. JS Development Primer--http File Server
    • node. JS Development Primer--helloworld Re-analysis
    • Introduction to node. JS Development--Environment building and HelloWorld

Copyright NOTICE: This article is Foruok original article, without BO Master permission cannot reprint.

Getting Started with node. JS Development-SOCKET (socket) programming

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.