1 | #!/usr/bin/env node
|
2 | var WebSocketServer = require('websocket').server
|
3 | var http = require('http')
|
4 |
|
5 | class WebSocket {
|
6 | constructor (port, opt) {
|
7 | this.connection = null
|
8 | this.port = port
|
9 | this.opt = opt
|
10 | }
|
11 |
|
12 | start (callback) {
|
13 | this.server = http.createServer(function (request, response) {
|
14 | console.log((new Date()) + ' Received request for ' + request.url)
|
15 | response.writeHead(404)
|
16 | response.end()
|
17 | })
|
18 | var loopback = '127.0.0.1'
|
19 | this.server.listen(this.port, loopback, function () {
|
20 | console.log((new Date()) + ' Remixd is listening on ' + loopback + ':65520')
|
21 | })
|
22 |
|
23 | this.wsServer = new WebSocketServer({
|
24 | httpServer: this.server,
|
25 | autoAcceptConnections: false,
|
26 | maxReceivedFrameSize: 131072,
|
27 | maxReceivedMessageSize: 10 * 1024 * 1024
|
28 | })
|
29 |
|
30 | this.wsServer.on('request', (request) => {
|
31 | if (!originIsAllowed(request.origin, this)) {
|
32 | request.reject()
|
33 | console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.')
|
34 | return
|
35 | }
|
36 | if (this.connection) {
|
37 | console.log('closing previous connection')
|
38 | this.wsServer.closeAllConnections()
|
39 | this.connection = null
|
40 | return
|
41 | }
|
42 |
|
43 | this.connection = request.accept('echo-protocol', request.origin)
|
44 | console.log((new Date()) + ' Connection accepted.')
|
45 | this.connection.on('message', (message) => {
|
46 | if (message.type === 'utf8') {
|
47 | callback(JSON.parse(message.utf8Data))
|
48 | }
|
49 | })
|
50 | this.connection.on('close', (reasonCode, description) => {
|
51 | console.log((new Date()) + ' Remix ' + this.connection.remoteAddress + ' disconnected.')
|
52 | this.connection = null
|
53 | })
|
54 | })
|
55 | }
|
56 |
|
57 | send (data) {
|
58 | this.connection.sendUTF(data)
|
59 | }
|
60 |
|
61 | close () {
|
62 | if (this.connection) {
|
63 | this.connection.close()
|
64 | this.connection = null
|
65 | }
|
66 | if (this.server) {
|
67 | this.server.close()
|
68 | this.server = null
|
69 | }
|
70 | }
|
71 | }
|
72 |
|
73 | function originIsAllowed (origin, self) {
|
74 | return origin === self.opt.remixIdeUrl
|
75 | }
|
76 |
|
77 | module.exports = WebSocket
|