WebSockets in node. js for Windows 7

Source: Internet
Author: User

Note: This was an update of my previous post on configuring WebSockets on a Windows 7 installation of node. js.

One of the lesser known features of HTML5 is WebSockets.  This is mainly due to a lack of browser support and standardization.  Still, there is a considerable amount of information available on the WebSockets API.  However, in order to create a WebSockets program, a corresponding server is required. Unfortunately, the process of creating a WebSockets server is not as well documented, and therefore acts as another hurdle towards widespread adoption.

This post provides step-by-step instructions for creating a simple WebSockets echo server.  The server allows developers to test client code by echoing-requests that it receives. The server is implemented in the node. JS framework, which can be run on a developer's local machine, eliminating the need For additional hardware.

node. js, written in C + + and JavaScript, allows users to rapidly create Web applications.  It is the well known for creating Web servers using Server-side JavaScript.  This post was based on version 0.8.6 of node. JS running on Windows 7.  I expect that the steps outlined below should is somewhat similar for other versions and operating systems. This isn't intended to be a node. js tutorial, but rather a guide to rapidly creating a WebSockets server.

Installing node. js

The first step is to install node. JS on your local machine.  node. JS can is downloaded from the project ' s homepage.  Download a prebuilt version of node. js by selecting the Windows Installer option.  Next, run the installer and locate the resulting node. JS installation directory.  On my machine, the installer configured node. js in the "C:\Program Files (x86) \nodejs" directory. If necessary, change the permissions of the ' Nodejs ' directory so that's you can create/modify files.

Installing the WebSockets Protocol

The node. JS Framework does not include native support for WebSockets, which means a third party solution is required. There is a number of WebSockets implementations available for node. js, but this tutorial focuses specifically on Theweb  Socket-node Project.  Websocket-node can easily configured using the Node package Manager, or NPM, which comes with node. js. To install Websocket-node, open a command line window and type the following commands:

CD "C:\Program Files (x86) \nodejs"npm install WebSocket

Starting with version 1.0.6 of Websocket-node, Windows users is also required to also install Microsoft Visual C + + and Py Thon 2.7 (not Python 3.x).

Creating the WebSockets Server

The node. JS Framework executes standalone JavaScript files.  In the ' Nodejs ' folder, create a file named ' ws_server.js '-this file would implement the Echo server.  The following code is taken directly from the Websocket-node GitHub page. Copy it into the ' ws_server.js ' file.

#!/usr/bin/env nodevarWebsocketserver = require (' WebSocket ')). server;varHTTP = require (' http ');varServer = Http.createserver (function(Request, Response) {Console.log (NewDate ()) + ' Received request for ' +Request.url); Response.writehead (404); Response.End ();}); Server.listen (8080,function() {Console.log (NewDate ()) + ' Server is listening on port 8080 ');}); WSServer=NewWebsocketserver ({httpserver:server,//You should don't use autoacceptconnections for production    //applications, as it defeats all standard Cross-origin protection    //facilities built into the protocol and the browser. You should    //*always* Verify the connection ' s origin and decide whether or not    //To accept it.Autoacceptconnections:false});functionOriginisallowed (origin) {//put logic detect whether the specified origin is allowed.  return true;} Wsserver.on (' Request ',function(Request) {if(!originisallowed (Request.origin)) {      //Make sure we have accept requests from an allowed OriginRequest.reject (); Console.log ((NewDate ()) + ' Connection from Origin ' + Request.origin + ' rejected. '); return; }    varConnection = request.accept (' Echo-protocol '), Request.origin); Console.log ((NewDate ()) + ' Connection accepted. '); Connection.on (' Message ',function(message) {if(Message.type = = = ' UTF8 ')) {Console.log (' Received Message: ' +message.utf8data);        Connection.sendutf (Message.utf8data); }        Else if(Message.type = = = ' binary ') {Console.log (' Received Binary Message of ' + message.binaryData.length + ' bytes ');        Connection.sendbytes (Message.binarydata);    }    }); Connection.on (' Close ',function(Reasoncode, description) {Console.log (NewDate ()) + ' Peer ' + connection.remoteaddress + ' disconnected. '); });});

Running the WebSockets Server

To start the server, type the following command:

Node Ws_server.js

If everything works properly, the server would display a message that it's listening on port 8080. The next step is to test the server using a client application. The corresponding WebSockets client is covered in this post.

WebSockets in node. js for Windows 7

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.