Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

426 CHAPTER 10 WebSocket communications


■■Author: your name
■■License: BSD


  1. Open the package.json file and add a dependency on the express and formidable
    packages as shown in the following modified package.json file.
    {
    "name": "chat_service",
    "version": "0.0.0",
    "description": "A simple chat service",
    "main": "app.js",
    "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
    },
    "repository": "",
    "author": "Glenn Johnson",
    "license": "BSD",
    “private”: true,
    “dependencies”: {
    “express”: “3.0.x”,
    “socket.io”: “0.9.x”
    }
    }

  2. Install the dependent packages by typing the following command.
    npm install

  3. Open Visual Studio Express 2012 for Web. Click File and choose Open Web Site; select
    the chat_service folder.

  4. In the chat_service website folder, create an app.js file and add a reference to the
    express, http, and socket.io packages. Call the listen method as follows.
    var express = require('express')
    , app = express()
    , http = require('http')
    , server = http.createServer(app)
    , io = require('socket.io').listen(server);


In this code, you are using the http object to create a server based on the express
object. After that, you are using the socket.io object to call the listen method and pass-
ing the server object to indicate the server that will be listening.


  1. In the Solution Explorer window, right-click the chat_service node, click Add, and
    choose New Folder. Name the folder public.

  2. In the app.js file, add a statement to map static requests to the /public folder as
    follows.
    app.use(express.static(__dirname + '/public'));

Free download pdf