Nodejs WebSocket Getting Started

Source: Internet
Author: User

WebSocket

2011 Technical Documentation

Http://www.ibm.com/developerworks/cn/web/1112_huangxa_websocket/index.html

Browser-side interface:

Https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API

websockets.org site: http://www.websockets.org/

Meet WebSocket

http://www.html5rocks.com/en/tutorials/websockets/basics/

Http://javascript.ruanyifeng.com/htmlapi/websocket.html

The HTTP protocol is a stateless protocol, and the server side itself does not have the ability to identify clients, and it must use external mechanisms such as sessions and cookies to keep conversations with specific clients. This is more or less inconvenient, especially if the server and the client need to constantly exchange data (such as Web chat). To solve this problem, HTML5 proposed the browser's WebSocket API.

The primary function of WebSocket is to allow full-duplex (Full-duplex) communication between the server and the client. For example, the HTTP protocol is a bit like emailing, and must wait for the other person to reply; WebSocket is like a phone call, and the server and client can send data to each other at the same time, and there is a continuously open data channel between them.

The WebSocket protocol can completely replace the Ajax method, which is used to send text and binary data to the server side, and there is no "domain restriction".

Nodejs Demo Installation

Https://github.com/websockets/ws

From

http://www.html5rocks.com/en/tutorials/websockets/basics/

Server Side implementations
  • node. js
    • Socket.io
    • Websocket-node
    • Ws

After downloading from Https://github.com/websockets/ws, unzip to the target directory, execute

npm install --save ws

For installation.

Encountered an error refusing to install Hapi as a dependency of itself:

Http://stackoverflow.com/questions/27267707/npm-warn-install-refusing-to-install-hapi-as-a-dependency-of-itself

Resolve by modifying name names in Package.json. such as Ws-test

To example folder, run node server.js result error:cannot find module ' xxx ' problem solved

The following methods are addressed:

http://blog.csdn.net/wmsjlihuan/article/details/19816389

Cannot find module ' xxx ' problem solving

Still reported after using NPM install-g ' xxx '
Cannot find module ' xxx ' error, can be resolved by setting environment variables;

Export node_path=/usr/local/lib/node_modules/
Echo $NODE _path

Run Results

[Email protected]:/home/share/ws-master/ws-master/examples/serverstats$ node Server.js

Started client interval
Stopping client interval
Started client interval
Stopping client interval

Page constantly refreshes data, soon! This content is pushed to the foreground by the background interval 200ms.

The code is as follows:

Server

varWebsocketserver = require ('.. /.. /‘). Server, HTTP= Require (' http '), Express= Require (' Express '), App=express.createserver (); App.use (Express.static (__dirname+ '/public ')); App.listen (8080);varWSS =Newwebsocketserver ({server:app}); Wss.on (' Connection ',function(WS) {varid = setinterval (function() {ws.send (Json.stringify () {process.memoryusage ()),function() {/*Ignore Errors*/ }); }, 100); Console.log (' Started client interval '); Ws.on (' Close ',function() {Console.log (' Stopping client interval ');  Clearinterval (ID); });});

Client

<!DOCTYPE HTML><HTML>  <Head>    <style>Body{font-family:Tahoma, Geneva, Sans-serif;      }Div{Display:inline;      }    </style>    <Script>      functionUpdateStats (memuse) {document.getElementById ('RSS'). InnerHTML=Memuse.rss; document.getElementById ('Heaptotal'). InnerHTML=Memuse.heaptotal; document.getElementById ('heapused'). InnerHTML=memuse.heapused; }      varHost=Window.document.location.host.replace (/:.*/, "'); varws= NewWebSocket ('ws://' +Host+ ': 8080'); Ws.onmessage= function(event) {UpdateStats (Json.parse (event.data));    }; </Script>  </Head>  <Body>    <Strong>Server Stats</Strong><BR>RSS:<DivID= ' RSS '></Div><BR>Heap Total:<DivID= ' Heaptotal '></Div><BR>Heap used:<DivID= ' heapused '></Div><BR>  </Body></HTML>

Evaluation

WebSocket is a new thing, browser support is different.

If you consider an older browser, you can use the Open source Commet framework, Pushlet:

Http://www.ibm.com/developerworks/cn/web/wa-lo-comet/index.html

For cases where only server push messages are required, you can use SSE

Http://server.ctocio.com.cn/181/13158181.shtml

http://www.html5rocks.com/en/tutorials/eventsource/basics/

Nodejs WebSocket Getting Started

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.