| 10 | |
| 11 | |
| 12 | function attachToServer(server, path) { |
| 13 | var WebSocketServer = require('ws').Server; |
| 14 | var wss = new WebSocketServer({ |
| 15 | server: server, |
| 16 | path: path |
| 17 | }); |
| 18 | var debuggerSocket, clientSocket; |
| 19 | |
| 20 | function send(dest, message) { |
| 21 | if (!dest) { |
| 22 | return; |
| 23 | } |
| 24 | |
| 25 | try { |
| 26 | dest.send(message); |
| 27 | } catch(e) { |
| 28 | console.warn(e); |
| 29 | // Sometimes this call throws 'not opened' |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | wss.on('connection', function(ws) { |
| 34 | const {url} = ws.upgradeReq; |
| 35 | |
| 36 | if (url.indexOf('role=debugger') > -1) { |
| 37 | if (debuggerSocket) { |
| 38 | ws.close(1011, 'Another debugger is already connected'); |
| 39 | return; |
| 40 | } |
| 41 | debuggerSocket = ws; |
| 42 | debuggerSocket.onerror = |
| 43 | debuggerSocket.onclose = () => { |
| 44 | debuggerSocket = null; |
| 45 | if (clientSocket) { |
| 46 | clientSocket.close(1011, 'Debugger was disconnected'); |
| 47 | } |
| 48 | }; |
| 49 | debuggerSocket.onmessage = ({data}) => send(clientSocket, data); |
| 50 | } else if (url.indexOf('role=client') > -1) { |
| 51 | if (clientSocket) { |
| 52 | clientSocket.onerror = clientSocket.onclose = clientSocket.onmessage = null; |
| 53 | clientSocket.close(1011, 'Another client connected'); |
| 54 | } |
| 55 | clientSocket = ws; |
| 56 | clientSocket.onerror = |
| 57 | clientSocket.onclose = () => { |
| 58 | clientSocket = null; |
| 59 | send(debuggerSocket, JSON.stringify({method: '$disconnected'})); |
| 60 | }; |
| 61 | clientSocket.onmessage = ({data}) => send(debuggerSocket, data); |
| 62 | } else { |
| 63 | ws.close(1011, 'Missing role param'); |
| 64 | } |
| 65 | }); |
| 66 | |
| 67 | return { |
| 68 | server: wss, |
| 69 | isChromeConnected: function() { |