Node. js development-socket programming, node. jssocket

Source: Internet
Author: User
Tags socket error

Node. js development-socket programming, node. jssocket

The net module of Node. js provides socket programming interfaces, so that we can use the underlying socket interfaces to implement application protocols. This time we will look at a simple echo server example, including the server and client code.

You can also use JavaScript For socket programming. Haha, this is cool!

Code

It can be divided into two parts: server and 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 creates a server instance. The return value of this method is a net. server instance, net. server provides the listen method, allowing us to listen to a port to accept client connections, and also provides some attributes, for example, maxConnections can set the maximum number of concurrent connections on the server (when the number of connections on the server exceeds this value, the connection will be rejected later). For more information, see https://nodejs.org/api/net.html#net_class_net_server.

Net. Server also provides some events, such as error and connection. When a client connection is accepted, a connection event is triggered, which includes a net. Socket object as a parameter. You can access the net. Socket instance in the callback function to interact with the client. In the code, I passed a callback to the createServer method to handle the connection event. In fact, I can also slightly modify it to process client connections 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 results are the same.

Net. Socket objects have some methods, such as writing data. There are also some events, such as error, end, and data. You can see the code to understand the usage. There are also some attributes, such as remoteAddress and remotePort.

I processed the data event. The data event has a parameter that represents the read data. In the callback, I directly use net. Socket. write to unseal the data and send it back to the client. This is an implementation of echo. Another more convenient implementation is to call the pipe method of net. Socket. The echoServer provided in the Node. js net module document is pipe.

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 longer. Because I want echo to be more like echo, I call the readline module to read data from the standard input and send it to the client. The readline documentation is here: https://nodejs.org/api/readline.html. Just like its name, Readline allows you to read a stream in one row. It is common to read standard input streams. There are some events in Readline. The "line" event we use will be launched when a row of data is ready, with a parameter representing the data. I listen to the line event and call the net. Socket write method in the callback to write data. When you enter "quit" or "exit" in the console, call quitEcho to exit.

The net. connect method can be used to connect to a specified server. Its prototype is as follows:

net.connect(options[, connectionListener])

The first parameter is an Object used to specify connection-related options, such as host and port on the server. If host is not specified, localhost is used as the server host name by default. In this example, only the port is specified.

Net. connect returns the net. Socket object. Once the Socket instance is obtained, you can use net. Socket to do whatever you want. I listened to the data event to receive the data played by the server, and listened to the close event to exit the process. For specific API of net. Socket, refer to https://nodejs.org/api/net.html#net_class_net_socket.

Running example

There is a saying in the comments that the time is too late. Well, you can run it. Run "node echoServer. js" and then "node echoClient. js" to enter some content on the echoClient console interface. The effect is as follows:

Other articles:

  • Getting started with Node. js development-notepad ++ for Node. js
  • Getting started with Node. js Development -- use the ngDialog dialog box
  • Getting started with Node. js Development -- introducing UIBootstrap
  • Getting started with Node. js development-using MongoDB to transform LoginDemo
  • Getting started with Node. js development-MongoDB and Mongoose
  • Getting started with Node. js development-Keep logging on with cookies
  • Get started with Node. js development-use AngularJS built-in services
  • Get started with Node. js development-Angular simple example
  • Get started with Node. js development-use AngularJS
  • Getting started with Node. js Development -- using the jade template engine
  • Introduction to Node. js development-routing and middleware in Express
  • Getting started with Node. js development-install and use Express
  • Node. js development-HTTP File Server
  • Getting started with Node. js Development -- HelloWorld Analysis
  • Node. js development entry-Environment setup and HelloWorld

Copyright Disclaimer: This article is an original foruok article and cannot be reproduced without the consent of the blogger.

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.