当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript socket.io函数代码示例

本文整理汇总了TypeScript中socket.io函数的典型用法代码示例。如果您正苦于以下问题:TypeScript io函数的具体用法?TypeScript io怎么用?TypeScript io使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了io函数的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。

示例1: Symbol

import {registerFactory} from "@tsed/common";
import * as SocketIO from "socket.io";

/**
 *
 */
export interface SocketIOServer extends SocketIO.Server {}

/**
 *
 */
// tslint:disable-next-line: variable-name
export const SocketIOServer = Symbol("SocketIOServer");

registerFactory(SocketIOServer, SocketIO());
开发者ID:Romakita,项目名称:ts-express-decorators,代码行数:15,代码来源:SocketIOServer.ts

示例2: openResource

server.use('/api/account-user', accountUserRouter);
server.use('/api/account-organization', accountOrganizationRouter);
server.use('/api/account-organization-member', accountOrganizationMemberRouter);
server.use('/api/account-organization-member-role', accountMemberRoleRouter);
server.use('/api/account-invitation', accountInvitationRouter);

server.use('/api/sales-lead', salesLeadRouter);
server.use('/api/sales-lead-organization-member', salesLeadOrganizationMemberRouter);
server.use('/api/sales-lead-organization-member-role', salesLeadMemberRoleRouter);
server.use('/api/sales-lead-contact', salesLeadContactRouter);
server.use('/api/sales-lead-status', salesLeadStatusRouter);
server.use('/api/log-item', logItemRouter);
server.use('/api/log-item-type', logItemTypeRouter);

server.all(APP_BASE + '*', (req, res) =>
  res.sendFile(INDEX_DEST_PATH)
);

const httpServer = server.listen(PORT, () => {
  const url = 'http://localhost:' + PORT + APP_BASE;
  if (process.env.RESTART) {     
    console.log('Server restarted at: ', url);
  } else {
    openResource(url);
    console.log('Server started at: ', url);
  }
});

const socketIoServerService = new SocketIOCymplarService(socketIO(httpServer));

开发者ID:jnamla,项目名称:herokuTestCymplar,代码行数:29,代码来源:bootstrap.ts

示例3: express

/// <reference path="../typings/express/express.d.ts" />

import * as express from 'express';
import * as fs from 'fs';
import * as bodyParser from 'body-parser';
import * as http from 'http';
import * as socket from 'socket.io';
import * as session from 'express-session';

import {config} from './config/config';
import {DB} from './config/mongoose';
import {Passport} from './config/passport';

var app = express();
var server = http.Server(app);
var io = socket(server);
var passport = new Passport();

var db = new DB();
// configure app
app.use(express.static('client'));
app.use(bodyParser.json());
app.use(session({ secret: 'keyboard cat', resave: true, saveUninitialized: true }));
app.use(Passport.origin.initialize());
app.use(Passport.origin.session());

// load controllers
fs.readdirSync('server/controllers')
    .filter(f => !!f.match(/\.js$/))
    .forEach(name => {
        var ctrlName = name.match(/([\w]*)Controller/)[1].toLowerCase();
开发者ID:dudko-av,项目名称:personal-app,代码行数:31,代码来源:server.ts

示例4: express

import * as express from 'express';
import * as http from 'http';
import * as socketio from 'socket.io';
import { ChatServer } from './lib/ChatServer/ChatServer';

var app = express();
var server = http.createServer(app);
var io: SocketIO.Server = socketio(server);

var port: number = 3000;

app.get('/', (request: any, response: any) => {
  response.sendFile(__dirname + '/public/htmls/index.html');
});

app.use('/static', express.static('public'));
app.use('/modules', express.static('node_modules'));

server.listen(port, () => {
  console.log('listening on port ' + port);
});

var chatServer = new ChatServer(server);
开发者ID:SuarezCanoDavid,项目名称:nodejsLearning,代码行数:23,代码来源:index.ts

示例5: start

export default function start(serverDataPath: string) {
  dataPath = serverDataPath;
  SupCore.log(`Using data from ${dataPath}.`);
  process.on("uncaughtException", onUncaughtException);

  loadConfig();

  const { version, superpowers: { appApiVersion: appApiVersion } } = JSON.parse(fs.readFileSync(`${__dirname}/../package.json`, { encoding: "utf8" }));
  SupCore.log(`Server v${version} starting...`);
  fs.writeFileSync(`${__dirname}/../public/superpowers.json`, JSON.stringify({ version, appApiVersion, hasPassword: config.server.password.length !== 0 }, null, 2));

  // SupCore
  (global as any).SupCore = SupCore;
  SupCore.systemsPath = path.join(dataPath, "systems");

  // List available languages
  languageIds = fs.readdirSync(`${__dirname}/../public/locales`);
  languageIds.unshift("none");

  // Main HTTP server
  mainApp = express();

  mainApp.use(cookieParser());
  mainApp.use(handleLanguage);

  mainApp.get("/", (req, res) => { res.redirect("/hub"); });
  mainApp.get("/login", serveLoginIndex);
  mainApp.get("/hub", enforceAuth, serveHubIndex);
  mainApp.get("/project", enforceAuth, serveProjectIndex);

  mainApp.use("/projects/:projectId/*", serveProjectWildcard);
  mainApp.use("/", express.static(`${__dirname}/../public`));

  mainHttpServer = http.createServer(mainApp);
  mainHttpServer.on("error", onHttpServerError.bind(null, config.server.mainPort));

  io = socketio(mainHttpServer, { transports: [ "websocket" ] });

  // Build HTTP server
  buildApp = express();

  buildApp.get("/", redirectToHub);
  buildApp.get("/systems/:systemId/SupCore.js", serveSystemSupCore);

  buildApp.use("/", express.static(`${__dirname}/../public`));

  buildApp.get("/builds/:projectId/:buildId/*", (req, res) => {
    const projectServer = hub.serversById[req.params.projectId];
    if (projectServer == null) { res.status(404).end("No such project"); return; }
    let buildId = req.params.buildId as string;
    if (buildId === "latest") buildId = (projectServer.nextBuildId - 1).toString();
    res.sendFile(path.join(projectServer.buildsPath, buildId, req.params[0]));
  });

  buildHttpServer = http.createServer(buildApp);
  buildHttpServer.on("error", onHttpServerError.bind(null, config.server.buildPort));

  loadSystems(mainApp, buildApp, onSystemsLoaded);

  // Save on exit and handle crashes
  process.on("SIGINT", onExit);
  process.on("message", (msg: string) => { if (msg === "stop") onExit(); });
}
开发者ID:alphafork,项目名称:Game-Engine-superpowers-core,代码行数:63,代码来源:start.ts

示例6: start

export async function start() {

  const app = express()

  const h = new http.Server(app)

  let global = io(h)
  global.on('connection', (clientSocket) => {
    console.log('connection from client namespace /')

    clientSocket.on('room', room => {
      console.log(`Joining room ${room} in namespace / `)
      clientSocket.join(room);
      global.sockets.in(room).emit('hello', 'heelo fellows')

    })

    clientSocket.on('disconnect', () => {
      console.log('client disconnected from / ')
    })

  })


  function notifyBUild(buildId) {
    testowa.in(`build${buildId}`).emit(`updatebuild${buildId}`, `updated buld ${buildId} !`)
  }

  const testowa = global.of('/testowa')
  testowa.on('connection', (clientSocket) => {
    console.log('connection from client namespace /testowa')

    clientSocket.on('roomSubscribe', room => {
      console.log(`Joining room ${room} in namespace /testowa `)
      clientSocket.join(room);
    })

    clientSocket.on('roomUnsubscribe', room => {
      console.log(`Leaving room ${room} in namespace /testowa `)
      clientSocket.leave(room);
    })

    setTimeout(() => {
      notifyBUild(12)
      notifyBUild(13)
    }, 2000)

    clientSocket.on('disconnect', () => {
      console.log('client disconnected from /testowa')
    })
  });



  app.use(cors())

  app.get('/users', (req, res) => {
    res.json([{ "name": "Bob from mockable.io", "id": 1 }, { "name": "Alice from mockable.io", "id": 2 }])
  })

  h.listen(port, async () => {
    console.log('Example app listening on port 3000!')
    console.log('test')
    try {
      const resp = await rest.model({
        test: 11
      }).array.get()
      console.log(JSON.stringify(resp.headers.toJSON()));
      console.log(JSON.stringify(resp.body.json))
    } catch (error) {
      console.log(error)
    }
  })



}
开发者ID:darekf77,项目名称:ng2-rest,代码行数:77,代码来源:index.ts

示例7: createServer

export default function createServer(
  { base, port, host, title }: Server,
  { key, cert }: SSLBuffer
): SocketIO.Server {
  const basePath = trim(base);
  events.emit(
    'debug',
    `key: ${key}, cert: ${cert}, port: ${port}, base: ${base}, title: ${title}`
  );

  const html = (
    req: express.Request,
    res: express.Response
  ): express.Response =>
    res.send(`<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <title>${title}</title>
    <link rel="stylesheet" href="${basePath}/public/index.css" />
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous">
  </head>
  <body>
    <div id="overlay">
      <div class="error">
        <div id="msg"></div>
        <input type="button" onclick="location.reload();" value="reconnect" />
      </div>
    </div>
    <div id="options">
      <a class="toggler"
         href="#" 
         alt="Toggle options"><i class="fas fa-cogs"></i></a>
      <textarea class="editor"></textarea>
    </div>
    <div id="terminal"></div>
    <script src="${basePath}/public/index.js"></script>
  </body>
</html>`);

  const app = express();
  app
    .use(morgan('combined', { stream: logger.stream }))
    .use(helmet())
    .use(compression())
    .use(favicon(path.join(distDir, 'favicon.ico')))
    .use(`${basePath}/public`, express.static(distDir))
    .use((req, res, next) => {
      if (
        req.url.substr(-1) === '/' &&
        req.url.length > 1 &&
        !/\?[^]*\//.test(req.url)
      )
        res.redirect(301, req.url.slice(0, -1));
      else next();
    })
    .get(basePath, html)
    .get(`${basePath}/ssh/:user`, html);

  return socket(
    !isUndefined(key) && !isUndefined(cert)
      ? https.createServer({ key, cert }, app).listen(port, host, () => {
          events.server(port, 'https');
        })
      : http.createServer(app).listen(port, host, () => {
          events.server(port, 'http');
        }),
    { path: `${basePath}/socket.io` }
  );
}
开发者ID:krishnasrinivas,项目名称:wetty,代码行数:72,代码来源:server.ts

示例8: start

    public start(existingApp?: Express) {
        if (!this.configuration) {
            this.logger.error(
                chalk.red(
                    `no configuration, you must either call 'configure()' or 'configureFromFile()' before starting MozaĂŻk server`
                )
            )
            process.exit(1)
        }

        if (
            this.configuration.apis !== undefined &&
            this.configuration.apis.pollInterval !== undefined
        ) {
            this.bus.pollInterval = this.configuration.apis.pollInterval
            this.logger.info(`set global APIs poll interval to ${this.bus.pollInterval}`)
        }

        this.bus.registerApi('mozaik', CoreApi(this.bus))

        const app = existingApp || express()

        app.use(cors())

        const baseDir = (this.configuration.baseDir || process.cwd()) + path.sep
        logger.info(chalk.yellow(`serving static contents from ${baseDir}build`))
        app.use(express.static(`${baseDir}/build`))

        app.get('/config', (req: Request, res: Response) => {
            // apis might contain sensible info
            res.send(omit(this.configuration, 'apis'))
        })

        const server = http.createServer(app)

        this.socket = SocketIO(server as any, {
            // client is installed as an autonomous package on the UI
            serveClient: false,
        })

        this.socket.on('error', (error: Error) => {
            this.logger.error(chalk.red(error.message), error)
        })

        this.socket.on('connection', (client: Socket) => {
            this.bus.addClient(client)

            client.on('api.subscription', (subscription: Subscription) => {
                this.bus.subscribe(client.id, subscription)
            })
            client.on('api.unsubscription', (subscription: Subscription) => {
                this.bus.unsubscribe(client.id, subscription.id)
            })
            client.on('disconnect', () => {
                this.bus.removeClient(client.id)
            })
        })

        const port = process.env.PORT || this.configuration.port

        server.listen(port, this.configuration.host, () => {
            logger.info(chalk.yellow(`MozaĂŻk server started on port ${port}`))
        })
    }
开发者ID:plouc,项目名称:mozaik,代码行数:64,代码来源:mozaik.ts

示例9: express

import * as socketio from 'socket.io';
import * as http from 'http';
import * as express from 'express';
import { Message } from './channel';

const app = express();
const server = http.createServer(app);
const io = socketio(server);
const port = 8000;
const peers: string[] = [];

// Serve static content from the `app`
app.use(express.static(__dirname + '/../app'));

// When we receive a new connection/peer
io.on('connection', (socket: SocketIO.Socket) => {

  // keep track of all the peers
  peers.push(socket.id);

  socket.on('message', function(msg: Message) {
    console.info("RECV", msg.type, JSON.stringify(msg.content));

    if (msg.type == "findPeers") {
      // The peer requested more peers
      findPeers(socket);
    } else if (msg.type == "relay") {
      // The peer wants a message relayed to another
      relayToPeer(socket, msg);
    } else {
      console.warn("Unknown type", msg);
开发者ID:gitter-badger,项目名称:planktos,代码行数:31,代码来源:server.ts

示例10: socketIOInit

 private socketIOInit()
 {
     this._io = SocketIO(this._server);
     this._io.attach(this._server);
     SocketHandler.socketHandler(this._io);
 }
开发者ID:p0ody,项目名称:ff2ebook-node,代码行数:6,代码来源:Server.ts


注:本文中的socket.io函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。