本文整理汇总了TypeScript中net.createConnection函数的典型用法代码示例。如果您正苦于以下问题:TypeScript createConnection函数的具体用法?TypeScript createConnection怎么用?TypeScript createConnection使用的例子?那么, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了createConnection函数的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1: sendCommand
export function sendCommand(tag: string, cmd: string, callback: (code) => void) {
let cmdMap = {
'stop': COMMAND.STOP,
'restart': COMMAND.RESTART,
'status': COMMAND.STATUS,
'statusjson': COMMAND.STATUSJSON,
};
let command = cmdMap[cmd.toLowerCase()];
if (!command) {
console.error('Command is not supported');
return callback(1);
}
let path = util.format('/tmp/lightsword-%s.sock', tag);
let socket = net.createConnection(path, async () => {
await socket.writeAsync(new Buffer([command]));
let msg = await socket.readAsync();
console.info(msg.toString('utf8'));
socket.destroy();
callback(0);
});
socket.on('error', (err: Error) => { console.info(`${tag} is not running or unix socket error.`); callback(1); });
socket.setTimeout(5 * 1000);
}
示例2: it
it('should close the socket keeping the socket open but then keeping it no longer open', function (done) {
this.timeout(0);
var sock = net.createConnection(9002, 'localhost');
sock.on('connect', function () {
var socket = new TCPSocket(sock, socket_opts);
var closeList1 = function () {
throw new Error('Should not close socket');
};
socket.once('close', closeList1);
socket.setKeepOpen(true);
setTimeout(function () {
socket.removeListener('close', closeList1);
socket.once('close', function () {
done();
});
socket.setKeepOpen(false);
}, 3000);
});
});
示例3: async
const listen = async () => {
listening = true
// We want to keep trying to reconnect here, so the dashboard can be restarted.
while (true) {
console.log('Connecting to monitoring server at', host)
const socket = net.createConnection(+port, host)
serveToSocket(localStore, socket)
socket.on('connect', () => {console.log('connected')})
await new Promise(resolve => {
socket.on('error', err => {
console.warn('Error connecting to monitoring server', err.message)
})
socket.on('close', hadError => {
// console.log('closed', hadError)
resolve()
})
})
// Wait 3 seconds before trying to connect again.
await new Promise(resolve => setTimeout(resolve, 3000))
}
}
示例4: handleOutbound
function handleOutbound(client: net.Socket, host: string, port: number, desiredIv: Buffer, options: HandshakeOptions) {
let proxy = net.createConnection({ port, host }, async () => {
let success = new Buffer([0x01, 0x00]);
let randomLength = Number((Math.random() * 64).toFixed());
let reply = Buffer.concat([success, new Buffer(randomLength)]);
let cipher = cryptoEx.createCipher(options.cipherAlgorithm, options.password, desiredIv).cipher;
await client.writeAsync(cipher.update(reply));
let decipher = cryptoEx.createDecipher(options.cipherAlgorithm, options.password, options.iv);
let speed = options.speed;
let clientStream = speed > 0 ? client.pipe(new SpeedStream(speed)) : client;
clientStream.pipe(decipher).pipe(proxy);
let proxyStream = speed > 0 ? proxy.pipe(new SpeedStream(speed)) : proxy;
proxyStream.pipe(cipher).pipe(client);
});
function dispose() {
client.dispose();
proxy.dispose();
}
proxy.on('error', dispose);
proxy.on('end', dispose);
client.on('error', dispose);
client.on('end', dispose);
proxy.setTimeout(options.timeout * 1000);
client.setTimeout(options.timeout * 1000);
}
示例5: function
_this.resolve(endpoint, function (err, resolved) {
if (!_this.connecting) {
callback(new Error(CONNECTION_CLOSED_ERROR_MSG))
return
}
if (resolved) {
debug('resolved: %s:%s', resolved.host, resolved.port)
_this.stream = createConnection(resolved)
_this.sentinelIterator.reset(true)
callback(null, _this.stream)
} else {
const endpointAddress = endpoint.host + ':' + endpoint.port
const errorMsg = err
? 'failed to connect to sentinel ' + endpointAddress + ' because ' + err.message
: 'connected to sentinel ' + endpointAddress + ' successfully, but got an invalid reply: ' + resolved
debug(errorMsg)
eventEmitter('sentinelError', new Error(errorMsg))
if (err) {
lastError = err
}
connectToNext()
}
})
示例6: connectServer
static connectServer(client: net.Socket, dst: { port: number, addr: string }, request: Buffer, timeout: number) {
let proxySocket = net.createConnection(dst.port, dst.addr, async () => {
let reply = new Buffer(request.length);
request.copy(reply);
reply[0] = 0x05;
reply[1] = 0x00;
await client.writeAsync(reply);
proxySocket.pipe(client);
client.pipe(proxySocket);
});
function dispose() {
proxySocket.dispose();
client.dispose();
}
proxySocket.on('end', dispose);
proxySocket.on('error', dispose);
client.on('end', dispose);
client.on('error', dispose);
proxySocket.setTimeout(timeout);
client.setTimeout(timeout);
}
示例7: connect
connect(host: string, port: number, query: string, callback: IConnectCallback): void {
const errorListener = (err: any) => callback(err, undefined);
const socket = net.createConnection({ host: host, port: port }, () => {
socket.removeListener('error', errorListener);
// https://tools.ietf.org/html/rfc6455#section-4
const buffer = Buffer.alloc(16);
for (let i = 0; i < 16; i++) {
buffer[i] = Math.round(Math.random() * 256);
}
const nonce = buffer.toString('base64');
let headers = [
`GET ws://${host}:${port}/?${query}&skipWebSocketFrames=true HTTP/1.1`,
`Connection: Upgrade`,
`Upgrade: websocket`,
`Sec-WebSocket-Key: ${nonce}`
];
socket.write(headers.join('\r\n') + '\r\n\r\n');
const onData = (data: Buffer) => {
const strData = data.toString();
if (strData.indexOf('\r\n\r\n') >= 0) {
// headers received OK
socket.off('data', onData);
callback(undefined, new NodeSocket(socket));
}
};
socket.on('data', onData);
});
socket.once('error', errorListener);
}
示例8: createClientSocket
function createClientSocket(endpointUrl: string): Socket {
// create a socket based on Url
const ep = parseEndpointUrl(endpointUrl);
const port = parseInt( ep.port!, 10);
const hostname = ep.hostname!;
let socket: Socket;
switch (ep.protocol) {
case "opc.tcp:":
socket = createConnection({ host: hostname, port });
// Setting true for noDelay will immediately fire off data each time socket.write() is called.
socket.setNoDelay(true);
socket.setTimeout(0);
socket.on("timeout", () => {
debugLog("Socket has timed out");
});
return socket;
case "fake:":
socket = getFakeTransport();
assert(ep.protocol === "fake:", " Unsupported transport protocol");
process.nextTick(() => socket.emit("connect"));
return socket;
case "websocket:":
case "http:":
case "https:FF":
default:
throw new Error("this transport protocol is currently not supported :" + ep.protocol);
}
}
示例9: attach
export function attach({
reader: _reader,
writer: _writer,
proc,
socket,
}: Attach) {
let writer;
let reader;
logger.debug('proc');
logger.debug(proc);
if (socket) {
const client = createConnection(socket);
writer = client;
reader = client;
} else if (_reader && _writer) {
writer = _writer;
reader = _reader;
} else if (proc) {
writer = proc.stdin;
reader = proc.stdout;
}
if (writer && reader) {
const neovim = new NeovimClient({ logger });
neovim.attachSession({
writer,
reader,
});
return neovim;
}
throw new Error('Invalid arguments, could not attach');
}
示例10: before
before(function (done) {
var sock = net.createConnection(9002, 'localhost');
sock.on('connect', function () {
socket = new TCPSocket(sock, socket_opts);
done();
});
});