MCPcopy Create free account
hub / github.com/Moddable-OpenSource/moddable / server

Function server

modules/network/websocket/websocket.js:339–447  ·  view source on GitHub ↗
(message, value, etc)

Source from the content-addressed store, hash-verified

337*/
338
339function server(message, value, etc) {
340 let socket = this.socket;
341
342 if (!socket) return;
343
344 if (2 == message) {
345 if ((1 === this.state) || (2 === this.state)) {
346 while (true) {
347 let line = socket.read(String, "\n");
348 if (!line)
349 return; // out of data. wait for more.
350
351 if (this.line) {
352 line = this.line + line;
353 this.line = undefined;
354 }
355
356 if (10 != line.charCodeAt(line.length - 1)) { // partial header line, accumulate and wait for more
357trace("partial header!!\n"); //@@ untested
358 this.line = line;
359 return;
360 }
361
362 if ("\r\n" == line) { // empty line is end of headers
363 if (15 !== this.flags)
364 throw new Error("not a valid websocket handshake");
365
366 delete this.line;
367 delete this.flags;
368
369 let sha1 = new Digest("SHA1");
370 sha1.write(this.key);
371 delete this.key;
372 sha1.write("258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
373
374 let response = [
375 "HTTP/1.1 101 Web Socket Protocol Handshake\r\n",
376 "Connection: Upgrade\r\n",
377 "Upgrade: websocket\r\n",
378 "Sec-WebSocket-Accept: ", new Uint8Array(sha1.close()).toBase64(), "\r\n",
379 ]
380
381 if (this.protocol) {
382 response.push("Sec-WebSocket-Protocol: ", this.protocol, "\r\n");
383 delete this.protocol;
384 }
385 response.push("\r\n");
386
387 socket.write.apply(socket, response);
388
389 this.callback(Server.handshake); // websocket handshake complete
390
391 this.state = 3;
392 socket.callback = callback.bind(this);
393 value = socket.read(); // number of bytes available
394 if (0 !== value) // should be 0. unexpected to receive a websocket message before server receives handshake
395 socket.callback(2, value);
396 return;

Callers

nothing calls this directly

Calls 8

writeMethod · 0.95
closeMethod · 0.95
toBase64Method · 0.80
readMethod · 0.65
closeMethod · 0.65
pushMethod · 0.45
callbackMethod · 0.45
bindMethod · 0.45

Tested by

no test coverage detected