MCPcopy
hub / github.com/socketio/socket.io / attach

Method attach

packages/engine.io/lib/server.ts:955–1005  ·  packages/engine.io/lib/server.ts::Server.attach

* Captures upgrade requests for a http.Server. * * @param {http.Server} server * @param {Object} options

(server: HttpServer, options: AttachOptions = {})

Source from the content-addressed store, hash-verified

953 * @param {Object} options
954 */
955 public attach(server: HttpServer, options: AttachOptions = {}) {
956 const path = this._computePath(options);
957 const destroyUpgradeTimeout = options.destroyUpgradeTimeout || 1000;
958
959 function check(req) {
960 class="cm">// TODO use `path === new URL(...).pathname` in the next major release (ref: https://nodejs.org/api/url.html)
961 return path === req.url.slice(0, path.length);
962 }
963
964 class="cm">// cache and clean up listeners
965 const listeners = server.listeners(class="st">"request").slice(0);
966 server.removeAllListeners(class="st">"request");
967 server.on(class="st">"close", this.close.bind(this));
968 server.on(class="st">"listening", this.init.bind(this));
969
970 class="cm">// add request handler
971 server.on(class="st">"request", (req, res) => {
972 if (check(req)) {
973 debug(class="st">'intercepting request for path "%s"', path);
974 this.handleRequest(req, res);
975 } else {
976 let i = 0;
977 const l = listeners.length;
978 for (; i < l; i++) {
979 listeners[i].call(server, req, res);
980 }
981 }
982 });
983
984 if (~this.opts.transports.indexOf(class="st">"websocket")) {
985 server.on(class="st">"upgrade", (req, socket, head) => {
986 if (check(req)) {
987 this.handleUpgrade(req, socket, head);
988 } else if (false !== options.destroyUpgrade) {
989 class="cm">// default node behavior is to disconnect when no handlers
990 class="cm">// but by adding a handler, we prevent that
991 class="cm">// and if no eio thing handles the upgrade
992 class="cm">// then the socket needs to die!
993 setTimeout(function () {
994 class="cm">// @ts-ignore
995 if (socket.writable && socket.bytesWritten <= 0) {
996 socket.on(class="st">"error", (e) => {
997 debug(class="st">"error while destroying upgrade: %s", e.message);
998 });
999 return socket.end();
1000 }
1001 }, destroyUpgradeTimeout);
1002 }
1003 });
1004 }
1005 }
1006}
1007
1008/**

Callers 8

attachFunction · 0.95
webtransport.mjsFile · 0.45
server.jsFile · 0.45
common.jsFile · 0.45
webtransport.mjsFile · 0.45
server.jsFile · 0.45
index.jsFile · 0.45
server.jsFile · 0.45

Calls 6

handleRequestMethod · 0.95
handleUpgradeMethod · 0.95
debugFunction · 0.85
bindMethod · 0.80
onMethod · 0.45
endMethod · 0.45

Tested by

no test coverage detected