constructor() {
     this.application = express();
     this.server = http.createServer(this.application);
 }
Beispiel #2
0
const router = new Router()

function getData(): Promise<any> {
    return new Promise((resolve, reject) => {
        request.get('https://store.steampowered.com/stats/').end((err, res) => {
            if (err) {
                reject(err)
            }
            const $ = cheerio.load(res.text), temp: object[] = []
            $('#detailStats tbody tr').each((index, item) => {
                temp.push({
                    cur: $(item).find('td:first-child').text().trim(),
                    name: $(item).find('td:last-child').text().trim(),
                    peak: $(item).find('td:nth-child(2)').text().trim(),
                })
            })
            resolve(temp)
        })
    })
}

router.get('/', async (ctx: Koa.Context, next: () => void) => {
    ctx.body = await getData()
})

app.use(router.routes())

http.createServer(app.callback()).listen(3344, () => {
    console.log(`http server listening on port: 3344`)
})
Beispiel #3
0
#!/usr/bin/env node

import * as http from 'http';
import * as app from '../app';

let server = http.createServer(app);
let port = process.env.port || '5000';

app.set('port', port);
server.listen(port);
console.log(`Server listening on port: ${port}`); 
Beispiel #4
0
/// <reference path="../typings/main/ambient/mime/index.d.ts" />
/// <reference path="../typings/main/ambient/mongoose/index.d.ts" />
/// <reference path="../typings/main/ambient/morgan/index.d.ts" />
/// <reference path="../typings/main/ambient/node/index.d.ts" />
/// <reference path="../typings/main/ambient/serve-static/index.d.ts" />

'use strict';

if ('production' === process.env.NODE_ENV)
    require('newrelic');

var PORT = process.env.PORT || 3333;

import * as express from 'express';
import * as os from 'os';
import * as http from 'http';
import {RoutesConfig} from './config/routes.conf';
import {DBConfig} from './config/db.conf';
import {Routes} from './routes/index';

const app = express();

RoutesConfig.init(app, express);
Routes.init(app, express.Router());

http.createServer(app)
    .listen(PORT, () => {
      console.log(`up and running @: ${os.hostname()} on port: ${PORT}`);
      console.log(`enviroment: ${process.env.NODE_ENV}`);
    });
import * as fs from 'fs';
import * as http from 'http';
import * as SocketIo from 'socket.io';
import { authorize, JwtSecretFuncCallback } from 'socketio-jwt';

const app = http.createServer((req: any, rsp: any) => {
	fs.readFile(__dirname + '/index.html',
		(err: Error | null, data: any) => {
			if (err) {
				rsp.writeHead(500);
				return rsp.end('Error loading index.html');
			}

			rsp.writeHead(200);
			rsp.end(data);
		});
});

const io = SocketIo(app);

// This example test code is using the Node Http Server

io.on('connection', authorize({
	secret: 'Your Secret Here',
	decodedPropertyName: 'anyNameYouWant'
}));

io.on('authenticated', (socket: SocketIo.Socket) => {
	console.log('authenticated!!');
	console.log(JSON.stringify((socket as any).anyNameYouWant));
});
import * as Express from "express";
import * as http from "http";

let app = Express();

app.set("port", process.env.PORT || 2900);
app.use(Express.static("public"));
app.use("/node_modules", Express.static("node_modules"));


http.createServer(app).listen(app.get("port"), () => {
  console.log("Express server listening on port " + app.get("port"));
});

//in case can't find path it's probably SPA so...
app.use(function(req: any, res: any, next: any) {
  res.status(200).sendFile("/public/index.html", { root: "./" });
});
Beispiel #7
0
        [GAME_STATE_READY]: new ReadyState(gameRoom),
        [GAME_STATE_IN_PROGRESS]: new InProgressState(gameRoom)
    })
});

const gameServer = new GameServer({ roomFactory });

//
// Providing the number of players online
//
const server = http.createServer(function(req, res) {
    
    if (req.url === `${config.httpPath}/player-count`) {
        res.writeHead(200, { 'Content-Type': 'application/json' });
        
        return res.end(JSON.stringify({
            playerCount: gameServer.playerCount
        }));
    }

    res.end();
});

//
// Websocket server
//
const wss = new WebSocketServer({
    server,
    path: config.wsPath
});

wss.on('connection', function(ws) {
                  callback({
                      name: args.name
                  });
              },
 
              // This is how to receive incoming headers 
              HeadersAwareFunction: function(args: any, cb: any, headers: any) {
                  return {
                      name: headers.Token
                  };
              },
 
              // You can also inspect the original `req` 
              reallyDeatailedFunction: function(args: any, cb: any, headers: any, req: any) {
                  console.log('SOAP `reallyDeatailedFunction` request from ' + req.connection.remoteAddress);
                  return {
                      name: headers.Token
                  };
              }
          }
      }
  };
 
var xml = fs.readFileSync('myservice.wsdl', 'utf8'),
    server = http.createServer(function(request,response) {
        response.end("404: Not Found: " + request.url);
    });
 
server.listen(8000);
soap.listen(server, '/wsdl', myService, xml);
Beispiel #9
0
import { createServer } from 'http';
import * as nconf from 'nconf'
import { Application } from './app';
import { Socket } from 'net';
import { MessageTypes } from './sharedParts/enums/messageTypes';

nconf.argv().env();

let port: number = nconf.get('port');
let messageServicePort = nconf.get('mServicePort');
let messageServiceHost = nconf.get('mServiceHost');

let app = new Application(MessageTypes);
let client = new Socket();

client.connect(messageServicePort, messageServiceHost, function() {
    console.log(`CONNECTED TO: ${messageServicePort}:${messageServiceHost}`);
});
let server = createServer(app.start(client));

server.listen(port, () => console.info(`Facebook chat bot server is listenning on port: ${port}`));
import * as http from 'http';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { NextObserver } from 'rxjs/Observer';

import 'rxjs/add/observable/merge';

import { RequestAction } from './RequestAction';
import { Emitable } from './Emitable';

import { aboutPage } from './pages/aboutPage';
import { welcomePage } from './pages/welcomePage';
import { notFoundPage } from './pages/notFoundPage';

const server: http.Server = http.createServer();

const requests$ = new Subject();

// Push data to RX
server.addListener(
    'request',
    (request, response) => requests$.next(new RequestAction(request, response))
);

// Combine services
const app = Observable.merge<RequestAction>(
        aboutPage(requests$),
        welcomePage(requests$),
        // If all previous routes failed we can return 404 response
        notFoundPage(requests$)
Beispiel #11
0
/**
 * Sockets Chat App
 * By Francisco Ortega (http://franciscoraulortega.com/), Alain Galvan (https://Alain.xyz)
 * Visit the page, and you'll be given a unique id and a default username you can rename with /nick <newname>
 * All previous messages in the chat are saved on the server.
 */

import * as Express from 'express';
import * as Http from 'http';
import * as Sockets from 'socket.io';

import chatSession from './chat-session';
import Commands from './chat-commands';

var app = Express();
var http = Http.createServer(app);
var io = Sockets(http);

var commands = Commands(io, chatSession);

// Routes
// Route all static files from the current directory + /public
// Route /chatapp to curdir + public/index.html
app.use(Express.static(__dirname + '/public'));
app.get('/chatapp', (req, res) => {
  res.sendFile(__dirname + '/public/index.html');
});

// Sockets
io.on('connection', (socket) => {
Beispiel #12
0
  console.log(moment(), "moment")

	r.db('howmidoin').table("data").insert({
		mood: request.body.mood,
		userId: request.params.id,
		date: Date.now()
	}).run(connection, function(err, result) {
    	if (err) throw err;
    	console.log(JSON.stringify(result, null, 2));
    	response.send('200')
	})
})

//DATA RETRIEVAL
app.get("/api/users/:id" , function(request, response) {
	r.db('howmidoin').table('data').filter({userId: request.params.id})
	.run(connection, function(err, cursor) {
		if (err) throw err;
    	cursor.toArray(function(err, result) {
        	if (err) throw err;
        	response.send(JSON.stringify(result, null, 2));
    	});
	})
})

app.get("*", function(request, response) {
  response.sendfile(path.join(__dirname, '..', 'public', 'index.html'));
});

http.createServer(app).listen(80);
Beispiel #13
0
http.createServer((request, response) => {
    // Create download object
    let download: IDownload = Object.create(options);
    download.chunks = Buffer.alloc(options.fileSize);
    download.bufferOffset = 0;
    download.aborted = false;
    download.readStreamOptions = {};
    download.headers = { 'Content-Length': download.fileSize };
    download.statusCode = 200;

    if (request.headers.range) {
        download.start = Number(request.headers
            .range.replace('bytes=', '').split('-')[0]);
        console.log(request.headers.range)
        download.readStreamOptions = { start: download.start };
        download.headers['Content-Range'] = `bytes ${download.start}-${download.fileSize}/download.fileSize`;
        download.statusCode = 206; //partial content
    }

    // Write Content-Length in headers
    response.writeHead(download.statusCode, download.headers);


    // Read data
    fs.createReadStream(download.file, download.readStreamOptions)
        .on('data', (chunk) => {
            // Store the file data in memory
            chunk.copy(download.chunks, download.bufferOffset);
            download.bufferOffset += chunk.length;
        })
        .once('open', () => {
            // start to throttle
            let handleAbort = throttle(download, (chunk: Buffer) => {
                response.write(chunk);
            });
            request.on('close', () => {
                handleAbort();
            });
        });

}).listen(8080);
Beispiel #14
0
import {IncomingMessage, ServerResponse} from "http";
import {Fields, Files} from "formidable";
import {Url} from "url";

var fs = require('fs');
var crypto = require('crypto');
var formidable = require('formidable');
var http = require('http');
var mkdirp = require('mkdirp');
var url_module = require('url');

//Path - full path to file with filename /var/lib/my.xml
//Dir - full path to file without filename and without trailing slash /var/lib

var httpServer = http.createServer(serverHandler);
httpServer.listen(80);

function serverHandler(req:IncomingMessage, res:ServerResponse) {

    console.log(req.url);
    var url:Url = url_module.parse(req.url, true);
    var jpgFile:string = url.query.jpgFile;
    var token:string = url.query.token;
    var customParam:string = url.query.customParam;

    if (url.pathname == '/crossdomain.xml') {
        res.writeHead(200, {"Content-Type": "text/xml"});
        var fileStream = fs.createReadStream('crossdomain.xml');
        fileStream.on('data', function (data) {
            res.write(data);
Beispiel #15
0
/// <reference path="../../typescript-interfaces/node.d.ts" />
import {Server, ServerRequest, ServerResponse, ClientResponse, ClientRequest} from "http";
var http = require('http');


var myServer:Server = http.createServer(handleRequests);

function traceErrorIfPresent(err:Error) {
    if (err) {
        console.error(err);
    }
}

function handleRequests(request:ServerRequest, response:ServerResponse) {
    console.log(request.headers);
    let requestBody:string = '';

    request.on('data', (chunk)=> {
        console.log(`chunk recived`);
        requestBody += chunk;
    });
    request.on('end', ()=> {
        console.log(requestBody);
    });
    request.on('error', traceErrorIfPresent);

    response.statusCode = 200;
    response.end('Hello Mother-father');
}

myServer.listen(3000);
import * as http from 'http'; // 1
 
const server = http.createServer((request, response)=> {
response.writeHead(200, {'Content-Type': 'text/application/json'});
//response.end('Hello World!\n');
response.end('{"message": "Hello Json!"}\n');
});
 
const port = 7000;
 
server.listen(port); // 2
console.log('Listening on http://localhost:' + port);

//To minimize manual coding we’ll install Express,
Beispiel #17
0
    constructor(ts:TetrisServer) {
        this.tServer = ts;
        let app = express();

        app.get('/', function (req, res) {
                fs.readFile('./client/core/index.html',
                    function (err, data) {
                        if (err) {
                            res.writeHead(500);
                            return res.end('Error loading index.html');
                        }

                        res.writeHead(200);
                        res.end(data.toString());
                    });

            }
        );

        app.get('/app.js', function (req, res) {
                fs.readFile('./client/dist/app.js',
                    function (err, data) {
                        if (err) {
                            res.writeHead(500);
                            return res.end('Error loading app.js');
                        }
                        res.writeHead(200, {
                            "Content-Type": "text/javascript"
                        });
                        res.end(data.toString());
                    });

            }
        );
        let server = http.createServer(app);
        let io = socketio.listen(server);
        let tServer:TetrisServer = this.tServer;

        io.sockets.on('connection', function (client) {
            client.join(client.id);
            //初めの接続でインスタンス生成
            tServer.connection(client.id)
                .then(()=>{
                })
                .catch(()=>{
                    io.sockets.to(client.id).emit('Error',"ページをリロードしてください");
                });

            client.on('disconnect',function(){
               tServer.disconnect(client.id);
            });

            /**
             * 準備をする、配列を返す通信
             */
            client.on('ready', function () {
                
                tServer.ready(client.id)
                    .then(list => {
                        io.sockets.to(client.id).emit('ready', list);
                    })
                    .catch(err =>{
                        io.sockets.to(client.id).emit('Error',err);
                    });
                    

            });

            /**
             * ブロックの検証受け付ける
             */
            client.on('verification', function (block:Block) {
                tServer.verid(client.id,block)
                    .then((score)=>{
                        io.sockets.to(client.id).emit('notifyScore',score);
                    })
                    .catch((msg:string)=>{
                       io.sockets.to(client.id).emit('Error',msg);
                    });
            });

            /**
             * ゲームの終了を受け付ける,ランキングを表示する
             */
            client.on('finishGame', function (name) {
                tServer.finishGame(client.id,name)
                    .then(list =>{
                        io.sockets.to(client.id).emit('ranking', list);
                    })
                    .catch(err =>{
                        io.sockets.to(client.id).emit('Error', err);

                    });
                
            });


        });
        server.listen(8080);
        console.log("8080:server");
    }
Beispiel #18
0
http.createServer(function (request: any, response: any) {
    // Allow calls from all domains, for all methods ans request headers.
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Credentials", true);
    response.setHeader("Access-Control-Allow-Methods", "*");
    response.setHeader("Access-Control-Allow-Headers", "*");
    response.setHeader("Cache-Control", "public, max-age=31536000");
    response.setHeader("Accept-Ranges", "bytes");
    response.setHeader("Expires", "Tue, 12 Dec 2017 11:11:34 GMT");
    response.setHeader("Last-Modified", "Tue, 14 Feb 2017 11:11:39 GMT");
    // response.setHeader("Vary", "Accept-Encoding");
    
    // parse URL
    const parsedUrl = url.parse(request.url);

    // extract URL path
    let pathname = `.${parsedUrl.pathname}`;

    // maps file extention to MIME types
    const mimeType: any = {
        '.ico': 'image/x-icon',
        '.html': 'text/html',
        '.js': 'text/javascript',
        '.json': 'application/json',
        '.css': 'text/css',
        '.png': 'image/png',
        '.jpg': 'image/jpeg',
        '.wav': 'audio/wav',
        '.mp3': 'audio/mpeg',
        '.svg': 'image/svg+xml',
        '.pdf': 'application/pdf',
        '.doc': 'application/msword',
        '.eot': 'appliaction/vnd.ms-fontobject',
        '.ttf': 'aplication/font-sfnt'
    };

    fs.exists(pathname, function (exist: any) {
        if (!exist) {
            // if the file is not found, return 404
            response.statusCode = 404;
            response.end(`File ${pathname} not found!`);
            return;
        }
        
        // if is a directory, then look for index.html
        if (fs.statSync(pathname).isDirectory()) {
            pathname += 'www/index.browser.html';
        }

        const ext = path.parse(pathname).ext;
        response.setHeader('Content-type', mimeType[ext] || 'text/plain');

        var raw = fs.createReadStream(pathname);
        var acceptEncoding = request.headers['accept-encoding'];
        if (!acceptEncoding) {
            acceptEncoding = '';
        }


        // Note: this is not a conformant accept-encoding parser.
        // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3

        // if (acceptEncoding.match(/\bdeflate\b/)) {
        //     response.writeHead(200, { 'Content-Encoding': 'deflate' });
        //     raw.pipe(zlib.createDeflate()).pipe(response);
        // } else 

        if (acceptEncoding.match(/\bgzip\b/)) {
            response.writeHead(200, { 'Content-Encoding': 'gzip' });
            raw.pipe(zlib.createGzip()).pipe(response);
        } else {
            response.writeHead(200, {});
            raw.pipe(response);
        }

        // read file from file system
        // Because all javascripts are loaded by the module loader, we don't directly read files from filesystem.
        // fs.readFile(pathname, function (err: any, data: any) {
        //     if (err) {
        //         res.statusCode = 500;
        //         res.end(`Error getting the file: ${err}.`);
        //     } else {
        //         // based on the URL path, extract the file extention. e.g. .js, .doc, ...
        //         const ext = path.parse(pathname).ext;
        //         // if the file is found, set Content-type and send data
        //         res.setHeader('Content-type', mimeType[ext] || 'text/plain');
        //         res.end(data);
        //     }
        // });
    });
}).listen(port, function () {
Beispiel #19
0
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use('/', routes);

// catch 404 and forward to error handler
app.use(function(req: Request, res: Response, next: NextFunction) {
  var err: any = new Error('Not Found');
  err.status = 404;
  next(err);
});

if (app.get('env') === 'development') {
  app.use(function(err: any, req: Request, res: Response, next: NextFunction) {
    res.status(err.status || 500);
    res.json({
      message: err.message,
      error: err
    });
  });
}

var server: Server = http.createServer(app);
server.listen(process.env.PORT || '4000');
server.on('listening', function() {
  var addr: any = server.address();
  var bind: string = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port;
  console.log('Listening on ' + bind);
});
Beispiel #20
0
// import {ActionRunner} from "../lib/lefrex/server/ActionRunner";
// import {AddFileAction} from "../messages/Files/actions/AddFileAction";
import FileRepository from "../data/repositories/Files/FileRepository";
import {QueueHost} from "../lib/kuku/host";
import {QueueClient} from "../lib/kuku/client";
import {FileAddedMessage} from "../messages/Files/queueMessages/FileAddedMessage";
// import {AddFileActionHandler} from "../domain/Files/ActionHandlers/AddFileActionHandler";
// import {UpdateFileDownloadStateAction} from "../messages/Files/actions/UpdateFileDownloadStateAction";
// import {UpdateFileDownloadStateActionHandler} from "../domain/Files/ActionHandlers/UpdateFileDownloadStateActionHandler";
// import {UpdateFileDownloadSpeedActionHandler} from "../domain/Files/ActionHandlers/UpdateFileDownloadSpeedActionHandler";
// import {UpdateFileDownloadProgressActionHandler} from "../domain/Files/ActionHandlers/UpdateFileDownloadProgressActionHandler";
// import {UpdateFileDownloadProgressAction} from "../messages/Files/actions/UpdateFileDownloadProgressAction";
// import {UpdateFileDownloadSpeedAction} from "../messages/Files/actions/UpdateFileDownloadSpeedAction";
// import {MessageQueue} from "../lib/kuku/MessageQueue";

const _httpServer = createServer();

_httpServer.listen({
    port: 8081
});

const _socketIoServer = socketIO(_httpServer);

// const _downloader = new Downloader();

interface ConnectedClient {
    socket: SocketIOClient.Socket;
}

const _connectedClients: ConnectedClient[] = [];
Beispiel #21
0
}

////////////////////////////////////////////////////
/// TLS tests : http://nodejs.org/api/tls.html
////////////////////////////////////////////////////

var ctx: tls.SecureContext = tls.createSecureContext({
    key: "NOT REALLY A KEY",
    cert: "SOME CERTIFICATE",
});
var blah = ctx.context;

////////////////////////////////////////////////////

// Make sure .listen() and .close() retuern a Server instance
http.createServer().listen(0).close().address();
net.createServer().listen(0).close().address();

var request = http.request('http://0.0.0.0');
request.once('error', function () {});
request.setNoDelay(true);
request.abort();

////////////////////////////////////////////////////
/// Http tests : http://nodejs.org/api/http.html
////////////////////////////////////////////////////
module http_tests {
    // Status codes
    var code = 100;
    var codeMessage = http.STATUS_CODES['400'];
    var codeMessage = http.STATUS_CODES[400];
Beispiel #22
0
import chat from '../server/chat';
import * as fs from 'fs';
import * as http from 'http';
import * as socketio from 'socket.io';

let server = http.createServer((req: http.IncomingMessage, res) => {
	let url = req.url;
	let path;
	if (fs.existsSync(__dirname + url) && fs.statSync(__dirname + url).isFile()) {
		path = __dirname + url;
	} else if (fs.existsSync(__dirname + '/..' + url) && fs.statSync(__dirname + '/..' + url).isFile()) {
		path = __dirname + '/..' + url;
	} else if (fs.existsSync(__dirname + '/../..' + url) && fs.statSync(__dirname + '/../..' + url).isFile()) {
		path = __dirname + '/../..' + url;
	} else {
		path = __dirname + '/index.html';
	}
	fs.readFile(path, (err: NodeJS.ErrnoException, data: Buffer) => {
		if (err) {
			res.writeHead(500);
			return res.end('Error loading index.html');
		}

		res.writeHead(200);
		res.end(data);
	});
});
const io: SocketIO.Server = socketio(server);
server.listen(3000);
chat(io);
var http = require('http');


var server = http.createServer((request, response)=> {
    response.writeHead(200, {'Content-Type': 'text/plain'});
    response.end('Hello World!\n');
});

var port = 8000;

server.listen(port);
console.log('Listening on http://localhost:' + port);
///<reference path='Definitions\node.d.ts' />

//This is a very simple http server.

var http = require('http');
var port = process.env.PORT || 1337;

http.createServer(function (req, res) {

    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Hello World from Node.js and TypeScript\n');

}).listen(port);
Beispiel #25
0
const server = http.createServer((req: http.IncomingMessage, res: http.ServerResponse) => {
    // Local variables
    let lookup = path.basename(decodeURI(req.url)) || 'index.html';
    let filePath = `${__dirname}/../content/${lookup}`

    // clean cache
    cache.clean(Date.now());

    // return cache
    if (cache[filePath]) {
        cache.clean(Date.now());
        let headers = { 'Content-type': mimeTypes[path.extname(lookup)] };
        res.writeHead(200, headers);
        res.end(cache[filePath].content)
        return;
    }

    // fs.exists had deprecated. Please use fs.stat() or fs.access()
    fs.access(filePath, (err: NodeJS.ErrnoException) => {
        // Response with 404
        if (err) { res.writeHead(404); res.end('Page not Found!'); return; }

        // Create read stream and build listeners
        let readStream = fs.createReadStream(filePath)
        readStream.once('open', () => {
            let headers = { 'Content-type': mimeTypes[path.extname(lookup)] };
            res.writeHead(200, headers);
            readStream.pipe(res);
        }).once('error', (err) => {
            console.log(err);
            res.writeHead(500);
            res.end('Server Error!');
        });

        // Store the file buffer in cache
        fs.stat(filePath, (err, stats) => {
            if (stats.size < cache.maxSize) {
                let bufferOffset = 0;
                cache.store[filePath] = {
                    content: Buffer.alloc(stats.size),
                    timestamp: Date.now(),
                };

                readStream.on('data', (chunk: Buffer) => {
                    chunk.copy(cache.store[filePath].content, bufferOffset);
                    bufferOffset += chunk.length;
                });
            }
        });

    });
}).listen(8080, () => {
Beispiel #26
0
import serveStatic = require('serve-static');
import {createServer} from 'http';
const finalhandler = require('finalhandler');

// Serve up public/ftp folder
const serve = serveStatic('public/ftp', {
    index: ['index.html', 'index.htm']
});

// Create server
const server = createServer((req, res) => {
  serve(req, res, finalhandler(req, res));
});

// Listen
server.listen(3000);
Beispiel #27
0
export default function () {
  const protractorGoodRegEx = /Jasmine started/;
  const webpackGoodRegEx = /: Compiled successfully./;

  // Create an express api for the Angular app to call.
  const app = express();
  const server = http.createServer(app);
  let liveReloadCount = 0;
  function resetApiVars() {
    liveReloadCount = 0;
  }

  server.listen(0);
  app.set('port', server.address().port);

  const firstLocalIp = _(os.networkInterfaces())
    .values()
    .flatten()
    .filter({ family: 'IPv4', internal: false })
    .map('address')
    .first();
  const publicHost = `${firstLocalIp}:4200`;

  const apiUrl = `http://localhost:${server.address().port}`;

  // This endpoint will be pinged by the main app on each reload.
  app.get('/live-reload-count', _ => liveReloadCount++);

  const proxyConfigFile = 'proxy.config.json';
  const proxyConfig = {
    '/live-reload-count': {
      target: apiUrl
    }
  };

  return Promise.resolve()
    .then(_ => writeMultipleFiles({
      'src/app/app.module.ts': `
        import { BrowserModule } from '@angular/platform-browser';
        import { NgModule } from '@angular/core';
        import { FormsModule } from '@angular/forms';
        import { HttpModule } from '@angular/http';
        import { AppComponent } from './app.component';
        @NgModule({
          declarations: [
            AppComponent
          ],
          imports: [
            BrowserModule,
            FormsModule,
            HttpModule
          ],
          providers: [],
          bootstrap: [AppComponent]
        })
        export class AppModule { }
      `,
      // e2e test that just opens the page and waits, so that the app runs.
      './e2e/app.e2e-spec.ts': `
        import { browser } from 'protractor';

        describe('master-project App', function() {
          it('should wait', _ => {
            browser.get('/');
            browser.sleep(30000);
          });
        });
      `,
      // App that calls the express server once.
      './src/app/app.component.ts': `
        import { Component } from '@angular/core';
        import { Http } from '@angular/http';

        @Component({
          selector: 'app-root',
          template: '<h1>Live reload test</h1>'
        })
        export class AppComponent {
          constructor(private http: Http) {
            http.get('${apiUrl + '/live-reload-count'}').subscribe(res => null);
          }
        }
      `
    }))
    .then(_ => execAndWaitForOutputToMatch(
      'ng',
      ['e2e', '--watch', '--live-reload'],
      protractorGoodRegEx
    ))
    // Let app run.
    .then(_ => wait(2000))
    .then(_ => appendToFile('src/main.ts', 'console.log(1);'))
    .then(_ => waitForAnyProcessOutputToMatch(webpackGoodRegEx, 10000))
    .then(_ => wait(2000))
    .then(_ => {
      if (liveReloadCount != 2) {
        throw new Error(
          `Expected API to have been called 2 times but it was called ${liveReloadCount} times.`
        );
      }
    })
    .then(_ => killAllProcesses(), (err) => { killAllProcesses(); throw err; })
    .then(_ => resetApiVars())
    // Serve with live reload off should call api only once.
    .then(_ => execAndWaitForOutputToMatch(
      'ng',
      ['e2e', '--watch', '--no-live-reload'],
      protractorGoodRegEx
    ))
    .then(_ => wait(2000))
    .then(_ => appendToFile('src/main.ts', 'console.log(1);'))
    .then(_ => waitForAnyProcessOutputToMatch(webpackGoodRegEx, 10000))
    .then(_ => wait(2000))
    .then(_ => {
      if (liveReloadCount != 1) {
        throw new Error(
          `Expected API to have been called 1 time but it was called ${liveReloadCount} times.`
        );
      }
    })
    .then(_ => killAllProcesses(), (err) => { killAllProcesses(); throw err; })
    .then(_ => resetApiVars())
    // Serve with live reload client set to api should call api.
    .then(() => writeFile(proxyConfigFile, JSON.stringify(proxyConfig, null, 2)))
    // Update the component to call the webserver
    .then(() => writeFile('./src/app/app.component.ts',
      `
        import { Component } from '@angular/core';
        import { Http } from '@angular/http';
        @Component({
          selector: 'app-root',
          template: '<h1>Live reload test</h1>'
        })
        export class AppComponent {
          constructor(private http: Http) {
            http.get('http://${publicHost + '/live-reload-count'}').subscribe(res => null);
          }
        }`))
    .then(_ => execAndWaitForOutputToMatch(
      'ng',
      ['e2e', '--watch', '--host=0.0.0.0', '--port=4200', `--public-host=${publicHost}`, '--proxy', proxyConfigFile],
      protractorGoodRegEx
    ))
    .then(_ => wait(2000))
    .then(_ => appendToFile('src/main.ts', 'console.log(1);'))
    .then(_ => waitForAnyProcessOutputToMatch(webpackGoodRegEx, 10000))
    .then(_ => wait(2000))
    .then(_ => {
      if (liveReloadCount != 2) {
        throw new Error(
          `Expected API to have been called 2 times but it was called ${liveReloadCount} times.`
        );
      }
    })
    .then(_ => killAllProcesses(), (err) => { killAllProcesses(); throw err; })
    .then(_ => server.close(), (err) => { server.close(); throw err; });
}
Beispiel #28
0
test('Wechaty.io Website smoking test', async t => {
  const httpServer = http.createServer()
  const ioServer = new IoServer({ httpServer })
  t.ok(ioServer, 'should instanciated an IoServer')
})
shield(app);
router(app);

let server: http.Server | https.Server;
let port: number;

if (config.https.enable) {
	port = config.port.https;
	server = https.createServer({
		key: fs.readFileSync(config.https.keyPath),
		cert: fs.readFileSync(config.https.certPath)
	}, app);

	http.createServer((req, res) => {
		res.writeHead(301, {
			Location: config.publicConfig.url + req.url
		});
		res.end();
	}).listen(config.port.http);
} else {
	port = config.port.http;
	server = http.createServer(app);
}

server.listen(port, () => {
	const listenhost: string = server.address().address;
	const listenport: number = server.address().port;

	console.log(
		`\u001b[1;32m${namingWorkerId(cluster.worker.id)} is now listening at ${listenhost}:${listenport}\u001b[0m`);
});
Beispiel #30
0
import { ChatRoom } from "./ChatRoom"

const port = Number(process.env.PORT || 2657);
const endpoint = "localhost";

if (cluster.isMaster) {
    // This only happens on the master server
    console.log("Starting master server.");
    console.log(`Running on Node.js ${process.version}.`);

    const cpus = os.cpus().length;
    for (let i = 0; i < cpus; ++i) {
        cluster.fork();
    }

} else {
    // This happens on the slave processes.

    // We create a new game server and register the room.
    const gameServer = new colyseus.Server({
        server: http.createServer(),
        presence: new colyseus.MemsharedPresence()
    });

    gameServer.register("chat", ChatRoom);
    gameServer.listen(port);

    console.log(`Listening on ws://${endpoint}:${port}`)
}