node. js and WebSocket implement Echo

Source: Internet
Author: User

Recently in learning node. JS, one of the chapters is about WebSocket-related content. The book I read is "Great node. js". An echo example was implemented in this book, but I made a mistake in the program I did on the book. The book uses the example of Express and Websocket.io implementations. However, the Express version of the example is still ancient 2.5.1, the latest is already 4. . , so it's not surprising that something is wrong.
The server code snippet in the book is probably this:

varrequire(‘express‘)    require("websocket.io")var app = express.createServer();var ws = wsio.attach(app);app.use(express.static(‘public‘));/* **/app.listen(3000);

The front-end code index.html as follows:

<! DOCTYPE html><html><head lang="en">    <meta charset="UTF-8">    <title>WebSocket Echo</title></head><body><H1>WebSocket Echo</H1><h2>Latency<span id="Latency"></span>Ms</H2><script>    varLastmessage; Window.onload= function(){        //create Socket        varWs=NewWebSocket (' ws://127.0.0.1:3000 '); ws.onopen= function(){            //send First PingPing ();        }; Console.log ("Going well!");//Monitor the closing of the socketWs.onclose = function(event) {Console.log (' Client notified socket has closed ', event);        }; Ws.onmessage= function(EV){Console.log ("Got:"+ev.data); document.getElementById ("Latency"). innerhtml=New Date-lastmessage;        Ping (); }; function ping(){Lastmessage =New Date; Ws.send ("Ping"); }    }</script></body><html>

Check the data only to know that the new version of Express has no createserver () this method. Then I refer to the Express 4.x API document to change the program, also can not solve, the browser displays "Connection closed before receiving a handshake response". Think about it, or feel like you don't understand express, so decide not to express, but to use HTTP directly.

varHTTP =require(' http ')//Use require (' Websocket.io ') if your installed with NPM, Wsio =require(' Websocket.io ')/** * Create HTTP server. * /varServer = Http.createserver ( function (req, res) {Res.writehead ( $, {' Content-type ':' text/html '}); Res.end ([' <! DOCTYPE html> ','     content of/*index.html * *,' ].join ("'));});varWS = Wsio.attach (server); Ws.on (' Connection ', function (socket) {Socket.on (' message ', function (msg) {Console.log (' \033[96mgot:\033[39m '+ msg); Socket.send (' Pong '); });}); Server.listen ( the);

The result of the operation is correct. However, this correct code looks uncomfortable, the front-end code and the server code are coupled, long string arrays I dare not put them up. And debugging is not clear at all, so I still want to use express static hosting function. Then continue to see the Express API. And then I saw the following:
var express = require (' Express ');
var http = require (' http ');
var app = Express ();
Http.createserver (APP). Listen (80);
The original app is actually a function, so you can use it to create a traditional httpserver. Then I got the following server-side code:

varExpress =require(' Express '), Wsio =require(' Websocket.io '), HTTP =require(' http ')varApp = Express (); app. Use(Express.Static(' Public '));varServer = Http.createserver (APP)varWS = Wsio.attach (server); Ws.on (' Connection ', function (socket) {Socket.on (' message ', function (msg) {Console.log (' \033[96mgot:\033[39m '+ msg); Socket.send (' Pong '); });}); Server.listen ( the);

The effect is also normal (index.html in the public subdirectory, and the content in the previous article is the same.) )

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

node. js and WebSocket implement Echo

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.