WebSockets in Node.js for Windows 7

NOTE:  This is 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 are 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 back any 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 well known for creating web servers using server-side JavaScript.  This post is based on version 0.8.6 of Node.js running on Windows 7.  I expect that the steps outlined below should be somewhat similar for other versions and operating systems.  This is not 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 be 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 you can create/modify files.

Installing the WebSockets Protocol

The Node.js framework does not include native support for WebSockets, which means that a third party solution is required.  There are a number of WebSockets implementations available for Node.js, but this tutorial focuses specifically on theWebSocket-Node project.  WebSocket-Node can be 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 are also required to also install Microsoft Visual C++ and Python 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 will 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 node
var WebSocketServer = require(‘websocket‘).server;
var http = require(‘http‘);

var server = http.createServer(function(request, response) {
    console.log((new Date()) + ‘ Received request for ‘ + request.url);
    response.writeHead(404);
    response.end();
});
server.listen(8080, function() {
    console.log((new Date()) + ‘ Server is listening on port 8080‘);
});

wsServer = new WebSocketServer({
    httpServer: server,
    // You should not 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
});

function originIsAllowed(origin) {
  // put logic here to detect whether the specified origin is allowed.
  return true;
}

wsServer.on(‘request‘, function(request) {
    if (!originIsAllowed(request.origin)) {
      // Make sure we only accept requests from an allowed origin
      request.reject();
      console.log((new Date()) + ‘ Connection from origin ‘ + request.origin + ‘ rejected.‘);
      return;
    }

    var connection = request.accept(‘echo-protocol‘, request.origin);
    console.log((new Date()) + ‘ 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((new Date()) + ‘ 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 will display a message that it is 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.

时间: 2024-10-08 16:53:04

WebSockets in Node.js for Windows 7的相关文章

用Node.js开发Windows 10物联网应用

(此文章同时发表在本人微信公众号"dotNET每日精华文章",欢迎右边二维码来关注.) 未来10年内,物联网将会如移动互联网这样深入到我们生活的各方各面.所以微软现在对物联网进行了大量的投资,比如Windows 10就有一个单独的IoT版本.而今天推荐的文章是告诉大家如何把Node.js开发带到Windows 10 IoT中. 在月初Build大会上,微软发布了Windows 10 IoT Core Insider Preview,这个版本可以安装到树莓派2(Raspberry Pi

node.js在windows下的学习笔记(2)---简单熟悉一些命令

1.打开如下的安装 2.输入node -v,显示node的版本号 3.输入node --help.显示帮助命令 4.自己用一个文本编辑器编写一下代码,保存为text.js,然后在控制台输入node.exe  text.js的路径(直接把这个js文件拖到控制台自动显示路径),按下回车键 var http = require("http"); http.createServer(function(request, response) { response.writeHead(200, {&

node.js在windows下的学习笔记(1)---安装node.js

1.首先打开http://www.nodejs.org/ 2.选择DOWNLOADS,跳转到下面的画面,我的系统是windows7的32位.所以选择.msi的32bit版本. 3.下载后,得到一个5.43MB大小的安装包, 4.运行安装包 点击next 打个勾,点击next 选择安装目录 最后,安装成功啦 node.js在windows下的学习笔记(1)---安装node.js,布布扣,bubuko.com

[Node.js]在windows下不得不防的小错误

TypeError: Arguments to path.join must be strings at f (path.js:204:15) at Object.filter (native) at exports.join (path.js:209:40) at exports.send (E:\nodejs\demo\socket.io-express\node_modules\express\node_modules\connect\lib\middleware\static.js:12

Node.js在Windows与Linux下的安装

一.Windows配置 (1)官网(http://nodejs.org)选择Node.js的Windows系统(32位和64位)最新版本. (2)下载完成后,执行MSI的安装文件. (3)安装完成,查看Node.js启动文件目录(右键单击Node.js启动快捷方式),启动文件目录一般默认情况下是在“C:\Program\nodejs\node.exe”. (4)将node.exe可执行文件路径添加到Windows的环境便令中:运行cmd,进入dos操作命令窗口,输入node -v查看是否安装成功

详细说明 配置 Sublime Text 开发node.js(windows)包括sub2和sub3的区别

1.先安装Sublime Text  2或者3皆可 2.下载 sublime Text 的nodejs插件 得到那个zip包(后面会介绍用Package Control安装) 3.下载后解压 直接改名为nodejs(一定是这个名字,否则sub2里编辑default文件会报错) 放到 Preferences-->浏览程序包Browse Packages所在的文件夹. 4.打开刚才的nodejs文件夹 找到根目录里面的 Nodejs.sublime-build文件 如下 { "cmd"

node.js之windows下环境终极配置

大家都知道现在node.js相当流行,出门在外,如果都没听说过node.js,基本上算是out了,前段时间做一个项目,用到了实时通讯功能,当时用的就是node.js来做的,我有幸有研究了一番,别的不敢说,环境配置应该是很熟练了.首先声明下,我用的是windows的环境,如果你用的是mac或Linux,那么可以绕道了. 第一,大家可以在node.js官网下载一个符合自己电脑的版本:https://nodejs.org/download/,如下图, 这里,我安装的windows installer.

node.js在windows下的学习笔记(3)---npm

1.什么是npm npm是Node.js的包管理器,它允许开发人员在Node.js的应用程序中创建,共享,重用模块.之前我们通过node的官网的安装程序安装了Node.js,那么npm就已经装好了的. 既然npm是Node.js的包管理器,那么什么是包呢? 包:包是一个文件夹,将模块封装起来,用于发布,更新,依赖管理,版本控制.你可以简单的把包理解成就是一个文件夹.package.json描述包的一些信息 模块:一个实现某些特定功能的文件,以实现模块化编程. 2.如何使用npm为node.js安

Node.js安装windows环境

转自:https://www.cnblogs.com/zhouyu2017/p/6485265.html 一.安装环境 1.本机系统:Windows 10 Pro(64位)2.Node.js:v6.9.2LTS(64位) 二.安装Node.js步骤 1.下载对应你系统的Node.js版本:https://nodejs.org/en/download/2.选安装目录进行安装3.环境配置4.测试 三.前期准备 1.Node.js简介简单的说 Node.js 就是运行在服务端的 JavaScript.