test("should successfully send a message with args", function(done: MochaDone) {
            const args = ["android"];
            let receivedMessage: ExtensionMessage;
            let receivedArgs: any;

            mockServer = net.createServer(function(client: net.Socket): void {
                mockServer.close();
                client.on("data", function(data: Buffer) {
                    const messageData: any = JSON.parse(data.toString("utf8"));
                    client.end();

                    receivedMessage = messageData.message;
                    receivedArgs = messageData.args;
                });
            });

            mockServer.on("error", done);
            mockServer.listen(port);

            const sender = RemoteExtension.atProjectRootPath(projectRootPath);

            Q({})
                .then(function() {
                    return sender.prewarmBundleCache(args[0]);
                })
                .then(function() {
                    assert.equal(receivedMessage, ExtensionMessage.PREWARM_BUNDLE_CACHE);
                    assert.deepEqual(receivedArgs, args);
                }).done(() => done(), done);
        });
test('correctly binds to the server and redirects its events.', () => {
  const server = createServer();
  proxifier.bind(server);

  const eventsAndListeners = new Map(
    ['listening', 'error', 'clientError', 'connection'].map(eventName => {
      const listener = jest.fn();
      proxifier.addListener(eventName, listener);

      return [eventName, listener] as [string, () => void];
    })
  );

  for (const [eventName, listener] of eventsAndListeners) {
    expect(listener).not.toHaveBeenCalled();

    // Emit several events, to make sure that server is not being listened with `once`.
    server.emit(eventName, 1, 2, 3, 4);
    server.emit(eventName, 5, 6, 7, 8);

    expect(listener).toHaveBeenCalledTimes(2);
    expect(listener).toHaveBeenCalledWith(1, 2, 3, 4);
    expect(listener).toHaveBeenCalledWith(5, 6, 7, 8);
  }
});
export function startLsCrashServer() {

    let pipe_path = generatePipeName(process.pid.toString(), 'vscode-language-julia-lscrashreports');

    let server = net.createServer(function (connection) {
        let accumulatingBuffer = new Buffer(0);

        connection.on('data', async function (c) {
            accumulatingBuffer = Buffer.concat([accumulatingBuffer, Buffer.from(c)]);
        });

        connection.on('close', async function (had_err) {
            let bufferResult = accumulatingBuffer.toString()
            let replResponse = accumulatingBuffer.toString().split("\n")
            let stacktrace = replResponse.slice(2,replResponse.length-1).join('\n');

            crashReporterQueue.push({exception: {name: replResponse[0], message: replResponse[1], stack: stacktrace}});

            traceEvent('lserror');

            if (enableCrashReporter) {
                sendCrashReportQueue();
            }
            else {
                showCrashReporterUIConsent();
            }
        });
    });

    server.listen(pipe_path);

    return pipe_path;
}
Beispiel #4
0
                PortFinder.getPort((err, port) => {
                    let fatJar = Path.resolve(context.extensionPath, "out", "fat-jar.jar");
                    
                    let args = [
                        '-cp', fatJar, 
                        '-Djavacs.port=' + port,
                        'org.javacs.Main'
                    ];
                    
                    console.log(javaExecutablePath + ' ' + args.join(' '));
                    
                    Net.createServer(socket => {
                        console.log('Child process connected on port ' + port);

                        resolve({
                            reader: socket,
                            writer: socket
                        });
                    }).listen(port, () => {
                        let options = { stdio: 'inherit', cwd: VSCode.workspace.rootPath };
                        
                        // Start the child java process
                        ChildProcess.execFile(javaExecutablePath, args, options);
                    });
                });
Beispiel #5
0
 constructor(options: { dstAddr: string, dstPort?: number, localPort?: number }) {
   let dstAddr = options.dstAddr;
   let dstPort = options.dstPort || defaultServerPort;
   let localPort = options.localPort || defaultServerPort;
   
   let server = net.createServer((socket) => {
     let transitSocket = net.createConnection(dstPort, dstAddr, () => {
       socket.pipe(transitSocket);
       transitSocket.pipe(socket);
     });
     
     function dispose() {
       transitSocket.dispose();
       socket.dispose();
     }
     
     transitSocket.on('end', dispose);
     transitSocket.on('error', dispose);
     socket.on('end', dispose);
     socket.on('error', dispose);
   });
   
   server.on('error', (err) => {
     console.log(err.message);
     process.exit(1);
   });
   
   server.listen(localPort);
 }
Beispiel #6
0
    function _getPort(portNumber: number) {
      if (portNumber > 65535) {
        reject(new Error(`There is no port available.`));
      }

      const server = net.createServer();

      server.once('error', (err: Error & {code: string}) => {
        if (err.code !== 'EADDRINUSE') {
          reject(err);
        } else if (port === 0) {
          _getPort(portNumber + 1);
        } else {
          // If the port isn't available and we weren't looking for any port, throw error.
          reject(
            new Error(`Port ${port} is already in use. Use '--port' to specify a different port.`),
          );
        }
      })
      .once('listening', () => {
        server.close();
        resolve(portNumber);
      })
      .listen(portNumber, host);
    }
        test("should successfully send a message", function(done: MochaDone) {
            let receivedMessage: ExtensionMessage;

            mockServer = net.createServer(function(client: net.Socket): void {
                mockServer.close();
                client.on("data", function(data: Buffer) {
                    const messageData: any = JSON.parse(data.toString("utf8"));
                    client.end();

                    receivedMessage = messageData.message;
                });
            });

            mockServer.on("error", done);
            mockServer.listen(port);

            const sender = RemoteExtension.atProjectRootPath(projectRootPath);

            Q({})
                .then(function() {
                    return sender.startPackager();
                })
                .then(function() {
                    assert.equal(receivedMessage, ExtensionMessage.START_PACKAGER);
                }).done(() => done(), done);
        });
Beispiel #8
0
  async start() {
    const broker = createMqttBroker()
    const server = createServer(broker.handle)
    this.server = server

    this.listenOn(
      plugin.interfaces.MQTT.id,
      plugin.interfaces.MQTT.events.publish.id,
      ({
        clientId,
        topic,
        value,
      }: {
        clientId: string
        topic: string
        value: string
      }) => {
        this.log.debug('Publishing packet', {
          clientId,
          topic,
          payload: value,
          qos: 0,
          retain: false,
        })
        const packet: IPublishPacket = {
          cmd: 'publish',
          topic,
          payload: value,
          qos: 0,
          retain: false,
          dup: false,
        }
        if (clientId) {
          ;(broker.publish as any)(packet, clientId, () => {})
        } else {
          broker.publish(packet, () => {})
        }
      },
    )

    broker.on('publish', (packet, client) => {
      this.log.debug('Received packet', {
        clientId: client && client.id,
        topic: packet.topic,
        value: packet.payload.toString(),
      })
      this.fireEvent(
        plugin.interfaces.MQTT.id,
        plugin.interfaces.MQTT.events.received.id,
        {
          clientId: client && client.id,
          topic: packet.topic,
          value: packet.payload.toString(),
        },
      )
    })

    await new Promise(resolve => server.listen(1883, resolve))
  }
Beispiel #9
0
export function findNextPort(port: number) {
  const server = net.createServer();
  return new Promise<number>((resolve) => {
    server.once("close", () => resolve(port));
    server.on("error", () => resolve(findNextPort(port + 1)));
    server.listen(port, () => server.close());
  });
}
test('correctly binds to the server.', () => {
  const server = createServer();
  jest.spyOn(server, 'addListener');
  proxifier.bind(server);

  expect(server.addListener).toHaveBeenCalledTimes(4);
  for (const eventName of ['listening', 'error', 'clientError', 'connection']) {
    expect(server.addListener).toHaveBeenCalledWith(eventName, expect.any(Function));
  }
});
Beispiel #11
0
    new Promise((resolve, reject) => {
      const nodeNet = require("net")
      const server = nodeNet.createServer()

      server.on("error", (err: any) => reject(err))
      server.on("listening", () => resolve(server))

      server.listen(p, host, () => {
        logger.info(`test server is up on port ${p}`)
      })
    })
Beispiel #12
0
  const createServer = (p: number) => new Promise((resolve, reject) => {
    const nodeNet = require("net");
    const server = nodeNet.createServer();

    server.on("error", (err: any) => reject(err));
    server.on("listening", () => resolve(server));

    server.listen(p, () => {
      logger.info(`test server is up on port ${p}`);
    });
  });
test('returns `address` from the underlying server.', () => {
  expect(proxifier.address()).toBeUndefined();

  proxifier.bind(createServer());

  expect(proxifier.address()).toEqual({
    address: 'test-address',
    family: 'test-family',
    port: 1234,
  });
});
test('correctly unbinds from the previous server.', () => {
  const previousServer = createServer();
  proxifier.bind(previousServer);

  const currentServer = createServer();
  proxifier.bind(currentServer);

  const eventsAndListeners = new Map(
    ['listening', 'error', 'clientError', 'connection'].map(eventName => {
      const listener = jest.fn();
      proxifier.addListener(eventName, listener);

      return [eventName, listener] as [string, () => void];
    })
  );

  // Any events from the previous server should not be forwarded.
  for (const [eventName, listener] of eventsAndListeners) {
    // `error` event is a special case in node, if `error` is emitted, but
    // there is no listener for it error will be thrown.
    if (eventName === 'error') {
      expect(() =>
        previousServer.emit(eventName, new Error('Some error'))
      ).toThrowErrorMatchingSnapshot();
    } else {
      previousServer.emit(eventName, 1, 2, 3, 4);
    }

    expect(listener).not.toHaveBeenCalled();
  }

  // Only events from the last server should be forwarded.
  for (const [eventName, listener] of eventsAndListeners) {
    expect(listener).not.toHaveBeenCalled();

    currentServer.emit(eventName, 1, 2, 3, 4);

    expect(listener).toHaveBeenCalledTimes(1);
    expect(listener).toHaveBeenCalledWith(1, 2, 3, 4);
  }
});
 isPortTaken(port: number, next: Function) {
   let tester = net.createServer()
   .once('error', (err: any) => {
     if (err.code != 'EADDRINUSE') return next(err)
     next(null, true)
   })
   .once('listening', function() {
     tester.once('close', function() { next(null, false) })
     .close()
   })
   .listen(port)
 }
 const result = await new Promise<boolean>(resolve => {
   // Start a server to check if we can listen to a port.
   server = net.createServer()
                .listen(port)
                .on('error',
                    () => {
                      // EADDRINUSE or EACCES, move on.
                      resolve(false);
                    })
                .on('listening', () => {
                  resolve(true);
                });
 });
Beispiel #17
0
            return await new Promise<number>((resolve, reject) => {
                const server = net.createServer()
                    .on('error', (error) => {
                        reject(error);
                    });

                server.listen(0, () => {
                    let port = server.address().port;

                    server.close(() => {
                        resolve(port);
                    });
                });
            });
Beispiel #18
0
function main(): void {
	let server = createServer((socket: Socket) => {

		process.stdout.write('Connection from ' + socket.remoteAddress + '\n');
		socket.end("Hello World\n");
		setTimeout(process.exit, 0);
	});

	// Fire up the server bound to port 7000 on localhost
	server.listen(7000, 'localhost');

	// Put a friendly message on the terminal
	process.stdout.write('TCP server listening on port 7000 at localhost.\n');
}
Beispiel #19
0
 return new Promise((resolve, reject) => {
   const server: any = net
     .createServer()
     .listen({ port, host, exclusive: true })
     .on("error", (e: any) => {
       if (e.code === "EADDRINUSE") {
         reject(new Error(`Port ${port} is unavailable on address ${host}`))
       } else {
         reject(e)
       }
     })
     .on("listening", () => {
       server.once("close", () => resolve()).close()
     })
 })
 return new Promise(resolve => {
     if (isNaN(port) || port != parseInt(port) || port < 0 || port > 65536) {
         // const err = 'Invalid input. Port must be an Integer number between 0 and 65536';
         // console.error(err);
         resolve(false);
     }
     port = parseInt(port);
     const tester = net.createServer()
         .once('error', err => {
             //console.error("Error: ", err);
             resolve(false);
         })
         .once('listening', () => tester.once('close', () => resolve(true)).close())
         .listen(port);
 });
test('returns connection count from the underlying server.', () => {
  const onGetConnectionsComplete = jest.fn();

  proxifier.getConnections(onGetConnectionsComplete);

  expect(onGetConnectionsComplete).toHaveBeenCalledTimes(1);
  expect(onGetConnectionsComplete).toHaveBeenCalledWith(null, 0);
  onGetConnectionsComplete.mockReset();

  proxifier.bind(createServer());
  proxifier.getConnections(onGetConnectionsComplete);

  expect(onGetConnectionsComplete).toHaveBeenCalledTimes(1);
  expect(onGetConnectionsComplete).toHaveBeenCalledWith(null, 100500);
});
Beispiel #22
0
 // https://gist.github.com/mikeal/1840641
 function _getPort (cb: (port: number) => void) {
   const server = net.createServer()
   server.on('error', (err) => {
     if (err) {/* fail safe */ }
     tryPort = nextPort(port)
     _getPort(cb)
   })
   server.listen(tryPort, (err: any) => {
     if (err) {/* fail safe */}
     server.once('close', () => {
       cb(tryPort)
     })
     server.close()
   })
 }
Beispiel #23
0
    return new Promise((resolve, reject) => {
        let net = require('net');
        let tester = net.createServer();
        tester.once('error', function (err) {
            if (err.code == 'EADDRINUSE') {
                resolve(false);
            }
        });
        tester.once('listening', function() {
            tester.close()
            resolve(true);

        });
        tester.listen(port);
    });
Beispiel #24
0
	constructor(serverOptions: SocketServerOptions, connectionListener: SocketServerListener, streamOptions: SocketOptions) {
		if (typeof (serverOptions) === 'function') {
			streamOptions = connectionListener;
			connectionListener = serverOptions;
			serverOptions = {};
		}
		var emitter = net.createServer(serverOptions, (connection) => {
			_.withContext(() => {
				_.run(_ => connectionListener(new SocketStream(connection, streamOptions || {}), _), (err?: Error) => {
					if (err) throw err;
				});
			})();
		});
		super(emitter);
	}
 return new Promise((resolve, reject) => {
   const tester = net.createServer()
   .once('error', (err: any) => {
     if (err.code !== 'EADDRINUSE') {
       return resolve(true);
     }
     resolve(true);
   })
   .once('listening', () => {
     tester.once('close', () => {
       resolve(false);
     })
     .close();
   })
   .listen(port, host);
 });
Beispiel #26
0
		ports.findFreePort(7000, 100, 300000).then(initialPort => {
			assert.ok(initialPort >= 7000);

			// create a server to block this port
			const server = net.createServer();
			server.listen(initialPort, void 0, void 0, () => {

				// once listening, find another free port and assert that the port is different from the opened one
				ports.findFreePort(7000, 50, 300000).then(freePort => {
					assert.ok(freePort >= 7000 && freePort !== initialPort);
					server.close();

					done();
				}, err => done(err));
			});
		}, err => done(err));
Beispiel #27
0
 return new Promise((resolve, reject) => {
   const tester = net.createServer()
   .once('error', () => {
     resolve(true);
   })
   .once('listening', () => {
     tester.once('close', () => {
       resolve(false);
     })
     .close();
   })
   .on('error', (err: any) => {
     reject(err);
   })
   .listen(port, host);
 });
Beispiel #28
0
		ports.findFreePort(7000, 100, 300000, (initialPort) => {
			assert.ok(initialPort >= 7000);

			// create a server to block this port
			const server = net.createServer();
			server.listen(initialPort, null, null, () =>  {

				// once listening, find another free port and assert that the port is different from the opened one
				ports.findFreePort(7000, 50, 0, (freePort) => {
					assert.equal(freePort, 0);
					server.close();

					done();
				});
			});
		});
Beispiel #29
0
 static start(tag: string) {
   let unixPath = util.format('/tmp/lightsword-%s.sock', tag);
   if (fs.existsSync(unixPath)) fs.unlinkSync(unixPath);
   
   let server = net.createServer(async (client) => {
     let data = await client.readAsync();
     let msg = '';
     let mem: { rss: number, heapTotal: number, heapUsed: number };
     
     switch(data[0]) {
       case COMMAND.STOP:
         msg = `${path.basename(process.argv[1])}d (PID: ${process.pid}) is going to quit.`;
         await client.writeAsync(new Buffer(msg));
         process.exit(0);
         break;
       case COMMAND.RESTART:
         let cp = child.spawn(process.argv[1], process.argv.skip(2).toArray(), { detached: true, stdio: 'ignore', env: process.env, cwd: process.cwd() });
         cp.unref();
         process.exit(0);
         break;
       case COMMAND.STATUS:
         mem = process.memoryUsage();
         msg = `${path.basename(process.argv[1])}d (PID: ${process.pid}) is running.`;
         msg = util.format('%s\nHeap total: %sMB, heap used: %sMB, rss: %sMB', msg, (mem.heapTotal / 1024 / 1024).toPrecision(2), (mem.heapUsed / 1024 / 1024).toPrecision(2), (mem.rss / 1024 / 1024).toPrecision(2));
         await client.writeAsync(new Buffer(msg));
         client.dispose();
         break;
       case COMMAND.STATUSJSON:
         mem = process.memoryUsage();
         let obj = {
           process: path.basename(process.argv[1]) + 'd',
           pid: process.pid,
           heapTotal: mem.heapTotal,
           heapUsed: mem.heapUsed,
           rss: mem.rss
         };
         await client.writeAsync(new Buffer(JSON.stringify(obj)));
         client.dispose();
         break;
     }
   });
   
   server.listen(unixPath);
   server.on('error', (err) => console.error(err.message));
 }
Beispiel #30
0
        it("Does not get enough keep alive", function(done) {
            let serverSocket: SocketHandler = null;
            let count = 0;

            let server: Server = net.createServer(function(socket: Socket) {
                serverSocket = new SocketHandler(socket, function () {
                    count++;
                    console.log("Count: " + count);

                    if (count < 10) {
                        serverSocket.send(new SocketMessage(Global.KeepAliveMessage));
                    } else {
                        // serverSocket.disconnect();
                    }
                });
            }).listen(9000);

            let socket = net.connect(9000, "localhost", function () {
                let handler = new SocketHandler(socket, function () {
                    keepAlive.received();
                });

                let keepAlive = new KeepAlive(handler);
                keepAlive.pingPeriod = 50;
                keepAlive.warningThreshold = 10;
                keepAlive.windowPeriod = 1000;

                let gotError = false;
                keepAlive.start(function () {
                    if (gotError) {
                        return;
                    }
                    gotError = true;
                    // This should get hit
                    keepAlive.stop();
                    socket.end();
                    server.close(function () {
                        done();
                    });
                });
            });
        });