Created
          November 14, 2022 21:02 
        
      - 
      
- 
        Save yakovenkodenis/60a6206dfe702fe99614e4748fcdd83c to your computer and use it in GitHub Desktop. 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | _init() { | |
| if (this._server) throw new Error('Server already initialized'); | |
| this._server = http.createServer((req, res) => { | |
| const UPGRADE_REQUIRED = 426; | |
| const body = http.STATUS_CODES[UPGRADE_REQUIRED]; | |
| res.writeHead(UPGRADE_REQUIRED, { | |
| 'Content-Type': 'text/plain', | |
| 'Upgrade': 'WebSocket', | |
| }); | |
| res.end(body); | |
| }); | |
| this._server.on('upgrade', (req, socket) => { | |
| this.emit('headers', req); | |
| if (req.headers.upgrade !== 'websocket') { | |
| socket.end('HTTP/1.1 400 Bad Request'); | |
| return; | |
| } | |
| const acceptKey = req.headers['sec-websocket-key']; | |
| const acceptValue = this._generateAcceptValue(acceptKey); | |
| const responseHeaders = [ | |
| 'HTTP/1.1 101 Switching Protocols', | |
| 'Upgrade: websocket', | |
| 'Connection: Upgrade', | |
| `Sec-WebSocket-Accept: ${acceptValue}`, | |
| ]; | |
| socket.write(responseHeaders.concat('\r\n').join('\r\n')); | |
| }); | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment