本文整理匯總了TypeScript中http.Server.on方法的典型用法代碼示例。如果您正苦於以下問題:TypeScript Server.on方法的具體用法?TypeScript Server.on怎麽用?TypeScript Server.on使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類http.Server
的用法示例。
在下文中一共展示了Server.on方法的7個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。
示例1: Promise
return protractorUtils.findFreeTcpPort().then(port => {
const app = new http.Server();
app.on('request', (req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('Hello World');
res.end('\n');
});
browser.baseUrl = `http://localhost:${port}`;
return new Promise(resolve => { app.listen(port, () => { resolve(); }); });
});
示例2: Promise
return new Promise((resolve) => {
const server = this.server = createServer((request: IncomingMessage, response: ServerResponse) => {
return this._handler(request, response);
});
this._sessions = {};
this._codeCache = {};
const sockets: Socket[] = [];
// If sockets are not manually destroyed then Node.js will keep itself running until they all expire
after(server, 'close', function () {
let socket: Socket;
while ((socket = sockets.pop())) {
socket.destroy();
}
});
server.on('connection', socket => {
this.executor.log('HTTP connection opened');
sockets.push(socket);
// Disabling Nagle improves server performance on low-latency connections, which are more common
// during testing than high-latency connections
socket.setNoDelay(true);
socket.on('close', function () {
let index = sockets.indexOf(socket);
index !== -1 && sockets.splice(index, 1);
});
});
this._wsServer = new WebSocket.Server({ port: this.port + 1 });
this._wsServer.on('connection', client => {
this.executor.log('WebSocket connection opened:', client);
this._handleWebSocket(client);
});
this._wsServer.on('error', error => {
this.executor.emit('error', error);
});
server.listen(this.port, resolve);
});
示例3: enhanceHttpServerWithSubscriptions
export async function enhanceHttpServerWithSubscriptions(
websocketServer: Server,
postgraphileMiddleware: HttpRequestHandler,
subscriptionServerOptions?: {
keepAlive?: number;
},
) {
if (websocketServer['__postgraphileSubscriptionsEnabled']) {
return;
}
websocketServer['__postgraphileSubscriptionsEnabled'] = true;
const {
options,
getGraphQLSchema,
withPostGraphileContextFromReqRes,
handleErrors,
} = postgraphileMiddleware;
const pluginHook = pluginHookFromOptions(options);
const graphqlRoute = options.graphqlRoute || '/graphql';
const schema = await getGraphQLSchema();
const keepalivePromisesByContextKey: { [contextKey: string]: Deferred<void> | null } = {};
const contextKey = (ws: WebSocket, opId: string) => ws['postgraphileId'] + '|' + opId;
const releaseContextForSocketAndOpId = (ws: WebSocket, opId: string) => {
const promise = keepalivePromisesByContextKey[contextKey(ws, opId)];
if (promise) {
promise.resolve();
keepalivePromisesByContextKey[contextKey(ws, opId)] = null;
}
};
const addContextForSocketAndOpId = (context: mixed, ws: WebSocket, opId: string) => {
releaseContextForSocketAndOpId(ws, opId);
const promise = deferred();
promise['context'] = context;
keepalivePromisesByContextKey[contextKey(ws, opId)] = promise;
return promise;
};
const applyMiddleware = async (
middlewares: Array<Middleware> = [],
req: IncomingMessage,
res: ServerResponse,
) => {
for (const middleware of middlewares) {
// TODO: add Koa support
await new Promise((resolve, reject) => {
middleware(req, res, err => (err ? reject(err) : resolve()));
});
}
};
const reqResFromSocket = async (socket: WebSocket) => {
const req = socket['__postgraphileReq'];
if (!req) {
throw new Error('req could not be extracted');
}
let dummyRes = socket['__postgraphileRes'];
if (req.res) {
throw new Error(
"Please get in touch with Benjie; we weren't expecting req.res to be present but we want to reserve it for future usage.",
);
}
if (!dummyRes) {
dummyRes = new ServerResponse(req);
dummyRes.writeHead = (statusCode: number, _statusMessage: never, headers: never) => {
if (statusCode && statusCode > 200) {
// tslint:disable-next-line no-console
console.error(
`Something used 'writeHead' to write a '${statusCode}' error for websockets - check the middleware you're passing!`,
);
socket.close();
} else if (headers) {
// tslint:disable-next-line no-console
console.error(
"Passing headers to 'writeHead' is not supported with websockets currently - check the middleware you're passing",
);
socket.close();
}
};
await applyMiddleware(options.websocketMiddlewares, req, dummyRes);
socket['__postgraphileRes'] = dummyRes;
}
return { req, res: dummyRes };
};
const getContext = (socket: WebSocket, opId: string) => {
return new Promise((resolve, reject) => {
reqResFromSocket(socket)
.then(({ req, res }) =>
withPostGraphileContextFromReqRes(req, res, { singleStatement: true }, context => {
const promise = addContextForSocketAndOpId(context, socket, opId);
resolve(promise['context']);
return promise;
}),
)
.then(null, reject);
//.........這裏部分代碼省略.........
示例4: handle
handle(cb: Function) {
this.httpServer.on('request', (request, response) => {
this.createContext(request, response, cb);
});
}
示例5: express
return new Promise<void>((resolve, reject) => {
const app = (this._app = express());
this._sessions = {};
this.executor.log(
'Listening for WebSocket connections on port',
this.socketPort
);
wsServer = new WebSocket.Server({ port: this.socketPort });
wsServer.on('connection', client => {
this.executor.log('WebSocket connection opened:', client);
this._handleWebSocket(client);
});
wsServer.on('error', error => {
if (isErrnoException(error) && error.code === 'EADDRINUSE') {
const err: NodeJS.ErrnoException = new Error(
`Something is already listening on the websocket server port (${
this.socketPort
})`
);
err.code = error.code;
err.errno = error.errno;
reject(err);
} else if (!this._wsServer) {
reject(error);
} else {
this.executor.emit('error', error);
}
});
const context = Object.create(null, {
stopped: {
enumerable: true,
get: () => this.stopped
},
basePath: {
enumerable: true,
get: () => this.basePath
},
executor: {
enumerable: true,
get: () => this.executor
},
handleMessage: {
enumerable: false,
writable: false,
configurable: false,
value: (message: Message) => this._handleMessage(message)
}
});
// Add "intern" object to both request and response objects
Object.defineProperty(app.request, 'intern', {
enumerable: true,
get: () => context
});
Object.defineProperty(app.response, 'intern', {
enumerable: true,
get: () => context
});
app.use(filterUrl());
// Handle JSON and form-encoded request bodies
app.use(json({ limit: '1mb' }), urlencoded({ extended: true }));
// Log all requests
app.use((request, _response, next) => {
this.executor.log(`${request.method} request for ${request.url}`);
return next();
});
const internPath = this.executor.config.internPath;
// Allow resolution using both __intern and node_modules/intern.
// Note that internPath will always end with a '/'.
app.use(
[`/${internPath}__resolveSuites__`, '/__intern/__resolveSuites__'],
resolveSuites(context)
);
// Map __intern to config.internPath
app.use('/__intern', express.static(internPath, { fallthrough: false }));
// TODO: Allow user to add middleware here
app.use(
instrument(context),
express.static(this.basePath),
post(context),
unhandled(),
finalError()
);
httpServer = app.listen(this.port, resolve);
httpServer.on('error', error => {
if (isErrnoException(error) && error.code === 'EADDRINUSE') {
const err: NodeJS.ErrnoException = new Error(
`Something is already listening on the server port (${this.port})`
//.........這裏部分代碼省略.........
示例6: require
import * as http from 'http';
import config from './config/config';
import { Socket } from './socket/index';
const app = require('./config/express').default();
const server: http.Server = new http.Server(app);
new Socket(server);
server.listen(config.port);
server.on('error', (e: Error) => {
console.log('Error starting server' + e);
});
server.on('listening', () => {
if (config.useMongo) {
console.log(`Server started on port ${config.port} on env ${process.env.NODE_ENV || 'dev'} dbcon ${config.mongodb}`);
} else {
console.log(`Server started on port ${config.port} on env ${process.env.NODE_ENV || 'dev'}`);
}
});
示例7: Error
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);
});