本文整理匯總了TypeScript中socket.io類的典型用法代碼示例。如果您正苦於以下問題:TypeScript io類的具體用法?TypeScript io怎麽用?TypeScript io使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
在下文中一共展示了io類的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。
示例1: function
var server = app.listen(config.port, function () {
var port = server.address().port;
app.io = SocketIO(server);
app.io.router = new MainIO();
app.io.router.initModules();
console.log('App listening at http://%s:%s', host, port);
});
示例2: createMessageHandler
export function createMessageHandler(httpServer: http.Server) {
d('init');
const io = ioServer(httpServer);
io.on('connection', socket => {
d('connection');
// Forward commands between connected clients. Parties involved can be the
// - The Cosmos UI, which acts as a remote control
// - The web iframe or the React Native component renderers
socket.on(RENDERER_MESSAGE_EVENT_NAME, msg => {
d('on renderer message %o', msg);
socket.broadcast.emit(RENDERER_MESSAGE_EVENT_NAME, msg);
});
});
function sendMessage(msg: BuildMessage) {
d('send server message %o', msg);
io.emit(SERVER_MESSAGE_EVENT_NAME, msg);
}
function cleanUp() {
const { sockets } = io.sockets;
Object.keys(sockets).forEach(id => {
sockets[id].disconnect(true);
});
}
return { sendMessage, cleanUp };
}
示例3: default
export default (server: Http.Server) => {
var io = SocketIO.listen(server);
io.on('connection', (socket: SocketIO.Socket) => {
//console.log('connected');
socket.on('join', (roomId: string) => {
//console.log('join: ', roomId);
socket.join(roomId);
//自分のみ
io.to(socket.id).emit('join', roomId);
});
socket.on('send', (comment: NicoNicoDesktop.IComment) => {
//console.log(comment);
io.to(comment.roomId).emit('flowing', comment);
});
socket.on('leave', (roomId: string) => {
//console.log('leave: ', roomId);
socket.leave(roomId);
//自分のみ
io.to(socket.id).emit('leave');
});
});
};
示例4: initializeNodeServer
initializeNodeServer() {
this.app = express();
this.http = http.Server(this.app);
this.io_http = socketio(this.http);
this.connMgr = new ConnectionManager(this.io_http);
this.registerView();
this.registerSocketIO();
}
示例5: main
function main() {
let sv = http.createServer((req, res) => {
res.writeHead(200, {"Content-Type": "text/plain"});
res.end("It works.");
});
sv.listen(8080);
let si = io.listen(sv);
si.sockets.on("connection", (socket) => {
socket.on("message", (data) => {
si.sockets.emit("message", "Message: <b>" + data.value + "</b>");
});
});
}
示例6: function
module.exports.create = function (bs, server, options) {
const socketConfig = options
.getIn(['socket', 'socketIoOptions'])
.toJS();
const socketServer = getSocketServer(options, server);
const io = socket(socketServer, socketConfig);
const clients = io.of(options.getIn(['socket', 'namespace']));
return {
socketServer,
io: io,
clients: clients,
protocol: {
send: function (path, arg) {
const data = proto.validate(path, arg);
if (data.errors.length) {
return data.errors.forEach(function (error) {
console.log(`Error type: ${error.errorType}, property: ${error.name}`);
});
}
clients.emit(data.payload.path, data.payload.args);
},
sendOptionToClient: function (client, id, options) {
const data = proto.validate('Options.set', id, options.toJS());
if (data.errors.length) {
return data.errors.forEach(function (error) {
console.log(`Error type: ${error.errorType}, property: ${error.name}`);
});
}
client.emit(data.payload.path, data.payload.args);
}
}
};
};
示例7: express
/// <reference path="../typings/main.d.ts" />
import * as express from "express";
const app: express.Application = express();
import {urlencoded, json} from "body-parser";
import * as io from "socket.io";
import {bruteForce} from "./helpers/bruteForce";
import * as expressJWT from "express-jwt";
import {key} from "./helpers/key";
let server = require("http").Server(app);
export let socketIO: SocketIO.Server = io.listen(server);
// importing routes
// complex
import {apiComplex} from "./routes/complex";
import {apiComplexes} from "./routes/complexes";
// entity
import {apiEntity} from "./routes/entity";
import {apiEntities} from "./routes/entities";
// object
import {apiObject} from "./routes/object";
import {apiObjects} from "./routes/objects";
// bim
import {apiBim} from "./routes/bim";
app.use(urlencoded({ extended: true }));
app.use(json());
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:*");
// res.header("Access-Control-Allow-Credentials", true);
示例8: sio
import sio from "socket.io";
import {getSession} from "./session";
import {User} from "./data/User"
export const SocketServer: SocketIO.Server = sio({transports: ["websocket"]});
export const SessionSocketMap = {};
const MainRoom: string = "Lobby";
// TODO middleware or some other solution to handle connection setup for authed users vs non-auth user
export function initSockets() {
SocketServer.on("connection", async (socket: SocketIO.Socket) => {
const session = getSession(socket.handshake)
SessionSocketMap[session.id] = socket
// Join user to Socket.io rooms for their own games
// TODO: Fail if not logged in?
const userId = session.passport.user
const gameIds = await User.getMyGames(userId)
gameIds.forEach(gameId => socket.join(`game:${gameId}`))
socket.join(`user:${userId}`)
socket.join(MainRoom)
});
}
export function notifyGame(gameId: string, message: string, data: any) {
console.log(`Sending message to game: ${gameId} ${message} ${JSON.stringify(data, null, 2)}`)
SocketServer.to(`game:${gameId}`).emit(message, data)
}
export function notifyLobby(message: string, data: any) {
console.log("Sending message to lobby")
示例9: express
import * as socketIO from 'socket.io';
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'public'), { maxAge: 86400 }));
app.use('/jspm_packages', express.static(path.join(__dirname, '../jspm_packages')));
var router = express.Router();
router.use((req, res, next) => next());
router.route('/test').get((req, res) => res.json({ test: 'ok' }));
router.get('/config.js', (req, res) => res.sendFile(path.join(__dirname, '../config.js')));
router.get('/socket.io-client.js', (req, res) => res.sendFile(path.join(__dirname, '../jspm_packages/npm/socket.io-client@1.4.6.js')));
app.use('/', router);
var server = app.listen(3000, 'localhost', () => {
console.log('App listening at http://%s:%s', server.address().address, server.address().port);
console.log(__dirname);
});
var io = socketIO.listen(server);
io.sockets.on('connection', function (socket) {
console.log("user connected");
socket.emit('helloWorld', { hello: 'world' });
});
示例10: require
/// <reference path="../typings/main.d.ts" />
try { require("source-map-support").install(); } catch (e) { /* empty */ }
import {IncomingMessage, ServerResponse} from "http";
import * as connect from "connect";
import * as serveStatic from "serve-static";
import * as SocketIOStatic from "socket.io";
const socket: SocketIOStatic = require("socket.io");
import {configure, getLogger} from "log4js";
configure({
appenders: [{ type: "console", layout: { type: "basic" } }],
"levels": { default: "INFO" }
});
let logger = getLogger();
import direct from "./scene/director";
let httpPort = process.argv[2] || "3000";
let wsPort = process.argv[3] || "3001";
let app = connect();
app.use("/wsport", (req: IncomingMessage, res: ServerResponse) => {
res.end(wsPort);
});
app.use(serveStatic("./lib/public/"));
app.listen(httpPort);
let io = socket(wsPort);
direct(io).catch(e => console.error(e.stack));
logger.info(`Server started: ${httpPort} ${wsPort}`);