Node. js development-UDP Programming

Source: Internet
Author: User
Tags sendmsg

Node. js development-UDP Programming

Node. js also provides UDP programming capabilities.DgramModule.

Unlike TCP, UDP is connectionless and does not guarantee data reliability. However, its programming is simpler and sometimes we need it. For example, for APP statistics, logs, or streaming media, many streaming media protocols use UDP, and a lot of data is searched on the Internet.

If you want to send data using UDP, you only need to know the host name (address) and port number of the other party and throw a message. If the recipient does not receive it, it is time to quit. This is the datagram service, similar to express delivery or mail.

We will introduce the UDP programming in Node. js this time. I will provide a UDP version of echoServer and echoClient.

General UDP Programming Model

Separate the client from the server.

Let's talk about the server first.

Server

As a UDP server, to receive messages from clients, there are several steps in Node. js:

Import the dgram module to create a socket to process the message event and bind the port

The following echoServer example shows the specific code.

Client

Client UDP programming is simpler. Just a few steps:

Import the dgram module and create a socket to send messages.

Of course, sometimes you may want the client to receive service messages. For example, if you send a message to the server and want the server to provide feedback, you also need to handle the message event and bind the port. For details, refer to our echoClient example.

API Introduction

To use the dgram module, you only need:

var dgram = require('dgram');

After dgram is introduced, you can use the createSocket method provided by it to create a socket. The createSocket method returns a dgram. Socket object, which provides a series of methods and events.

The bind method of dgram. Socket binds the socket and a port. For example, if the port of the echo service is 7, the following code snippet creates a socket and binds it to port 7:

var dgram = require('dgram');var serverSocket = dgram.createSocket('udp4');serverSocket.bind(7);

When a message arrives, dgram. Socket will launch a message event. We can monitor this event to process the message:

serverSocket.on('message', function(msg, rinfo){  ...});

The callback function corresponding to the message event has two parameters:BufferObject msg, representing the data sent by the client. Rinfo carries the remote host information. rinfo. address is the address of the remote host, and rinfo. port is the port of the remote host.

Dgram. Socket also contains "error", "close", and "listening" events. For more information, see the online documentation: https://nodejs.org/api/dgram.html.

To send data, you can call the dgram. send method as follows:

var msg = new Buffer('Hello Server');serverSocket.send(msg, 0, msg.length, 7, 127.0.0.1);
Example

EchoServerUdp. js implements our echoServer example. The Code is as follows:

var dgram = require('dgram');var serverSocket = dgram.createSocket('udp4');serverSocket.on('message', function(msg, rinfo){  console.log('recv %s(%d bytes) from client %s:%d', msg, msg.length, rinfo.address, rinfo.port);  //echo to client  serverSocket.send(msg, 0, msg.length, rinfo.port, rinfo.address);});//    err - Error object, https://nodejs.org/api/errors.htmlserverSocket.on('error', function(err){  console.log('error, msg - %s, stack - %s', err.message, err.stack);});serverSocket.on('listening', function(){  console.log(echo server is listening on port 7.);})serverSocket.bind(7);

EchoClientUdp. js implements the echo client. The Code is as follows:

var dgram = require('dgram');var clientSocket = dgram.createSocket('udp4');var messages = [  'Hello, Echo Server.',  'Are you OK?',  'I am happy.',  'A little panda found a pumpkin.'];var index = 0;function sendMsg(){//send to server  var msg = messages[index];  index = index + 1;  if(index == messages.length){    index = 0;  }  clientSocket.send(msg, 0, msg.length, 7, localhost);}//start a timer to send message to echoServersetInterval(sendMsg, 1000);clientSocket.on('message', function(msg, rinfo){  console.log('recv %s(%d) from server', msg, msg.length);});clientSocket.on('error', function(err){  console.log('error, msg - %s, stack - %s', err.message, err.stack);});clientSocket.bind(54321);

It seems that the client is more complex than the server, because as the echo client, I need to display the message sent by the server, so I also need to listen to a port (54321 In the example ). In addition, I still need to send data to the server, so I useSetIntervalA periodic timer is started to send messages in a string array cyclically.

SetInterval is a method provided by the global Object of Node. js to start a periodic timer. The prototype is as follows:

setInterval(cb, ms)

The first parameter is the callback function executed when the timer is triggered, and the second parameter is the timer cycle, in milliseconds. In our example, a message is sent to the server every 1000 milliseconds.

SetInterval returns a value that represents the timer. You can pass it to clearInterval to cancel the corresponding timer.

In addition, when handling error events of dgram. Socket, echoServer and echoClient use the Error object. The document is here: https://nodejs.org/api/errors.html.

Okay, the code is like this. You can open two command line windows and execute "node echoServerUdp. js" and "node echoClientUdp. js" respectively to observe the effect.

 

Related Article

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.