node. JS Development Primer-UDP Programming

Source: Internet
Author: User
Tags sendmsg socket error

node. JS also provides the ability to program UDP, and the related libraries are in the "dgram" module.

Unlike TCP, UDP is non-connected and does not guarantee the reliability of the data, but its programming is simpler and sometimes we need it. such as the statistics of the app or log or streaming media, a lot of streaming protocols will use UDP, a large number of online search.

Using UDP, if you want to send data, just need to know the host name (address) and port number, throw a message in the past can be. As for the other side to receive, resigned. This is the datagram service, similar to courier or Mail.

Let's introduce UDP programming in node. js, and I'll provide a UDP version of Echoserver and Echoclient.

General model of UDP programming

The client and the server are separated.

Let's start with the service side.

Service side

As a UDP server, to receive messages from clients, in node. js, there are roughly a few steps:

    1. Import Dgram Module
    2. Create socket (socket)
    3. Handling Message Events
    4. Binding port

We can see the specific code later in our Echoserver example.

Client

Client-side UDP programming is easier, a few steps, you can:

    1. Import Dgram Module
    2. Create socket (socket)
    3. Send Message

Of course, sometimes you may want the client to also receive service messages, such as you send a message to the server, you want the service side feedback, then you also need to handle the message event and bound port. Just look at our echoclient example.

API Introduction

To use the Dgram module, just do this:

var dgram = require(‘dgram‘);

Once Dgram is introduced, you can use the method createsocket it provides to create a socket. The Createsocket method returns a Dgram.socket object that provides a series of methods and events.

Dgram. The bind method of the socket binds the socket to a port, such as the Echo service port is 7, and the following code fragment creates a socket and binds to port 7:

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

Dgram when a message arrives. The socket emits a message event, and we listen to this event to process messages:

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

The message event corresponds to a callback function with two parameters, one is the Buffer object MSG, which represents the data sent over the client. One is rinfo, carrying the information of the remote host, rinfo.address is the address of the remote host, Rinfo.port is the port of the remote host.

Dgram. The socket also has "error", "Close", "listening" and other events, refer to the online documentation: Https://nodejs.org/api/dgram.html.

To send data, you can call the Dgram.send method, just like this:

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

Echoserverudp.js implements our Echoserver example with the following code:

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\n‘, 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\n‘, 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 with the following code:

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\n‘, msg, msg.length);});clientSocket.on(‘error‘, function(err){  console.log(‘error, msg - %s, stack - %s\n‘, err.message, err.stack);});clientSocket.bind(54321);

It seems that the client is more complicated than the server, because as the echo client, I need to display the message sent by the server, so I also need to hear a port (in the example 54321). In addition, I will continue to send data to the server, so with setinterval started a periodic timer, loop send a string array of messages inside.

The SetInterval is a method provided by the global object of node. js to start a recurring timer with the following prototype:

setInterval(cb, ms)

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

SetInterval returns a value that represents the timer, which you can pass to the clearinterval to cancel the corresponding timer.

In addition Echoserver and echoclient in handling the Dgram.socket Error event, the Error object is used, the document is here: https://nodejs.org/api/errors.html.

OK, so the code can open two command-line windows and execute "node Echoserverudp.js" and "node Echoclientudp.js" to see the effect.

Other articles:

    • Get started with node. JS-access to the outside world using HTTP
    • Getting Started with node. JS Development-SOCKET (socket) programming
    • 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.

node. JS Development Primer-UDP 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.