net#createConnection TypeScript Examples
The following examples show how to use
net#createConnection.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: withServerNoVM.spec.ts From Assistive-Webdriver with MIT License | 5 votes |
describe("with server and no vm", () => {
let subProcess: ChildProcess;
beforeAll(async () => {
const serverPath = require.resolve(
"assistive-playwright-server/assistive-playwright-server"
);
subProcess = fork(serverPath, [
"--http-port",
"8885",
"--tcp-port",
"8886"
]);
await waitPort({ port: 8885, timeout: 10000 });
}, 30000);
afterAll(async () => {
subProcess.kill("SIGINT");
await new Promise(done => subProcess.once("exit", done));
});
it("should create a page in chromium", async () => {
const { chromium } = connectRemotePlaywright("http://localhost:8885");
const instance = await chromium.launch();
try {
const context = await instance.newContext();
try {
const page = await context.newPage();
try {
const response = await page.goto("http://localhost:8885");
const json = await response!.json();
expect(json).toEqual({ server: "assistive-playwright-server" });
} finally {
await page.close();
}
} finally {
await context.close();
}
} finally {
await instance.close();
}
});
it("should receive messages from the screen reader", async () => {
const screenReader = await ScreenReaderClient.create(
"ws://localhost:8885/screen-reader"
);
expect(screenReader.connected).toBe(true);
const socketTCP = createConnection(8886, "127.0.0.1");
await new Promise(done => socketTCP.on("connect", done));
socketTCP.write("Hello world!\n");
await wait(100);
expect(await screenReader.waitForMessage(/Hello (\w+)!/)).toEqual([
"Hello world!"
]);
const nextMessage = screenReader.waitForMessage(/How are (\w+)?/);
const listener = jest.fn();
nextMessage.then(listener);
await wait(100);
expect(listener).not.toHaveBeenCalled();
socketTCP.write("How are you?\n");
expect(await nextMessage).toEqual(["How are you?"]);
await new Promise<void>(done => socketTCP.end(done));
screenReader.disconnect();
await wait(100);
expect(screenReader.connected).toBe(false);
});
});
Example #2
Source File: e2eWithoutVM.spec.ts From Assistive-Webdriver with MIT License | 4 votes |
describe("e2e without VM", () => {
let subProcess: ChildProcess;
beforeAll(async () => {
subProcess = fork(resolve(__dirname, "../assistive-playwright-server"), [
"--http-port",
"8883",
"--tcp-port",
"8884"
]);
await waitPort({ port: 8883, timeout: 10000 });
}, 30000);
afterAll(async () => {
subProcess.kill("SIGINT");
await new Promise(done => subProcess.once("exit", done));
});
it("should accept /screen-reader websocket connections", async () => {
const socketWeb = new Websocket("ws://127.0.0.1:8883/screen-reader");
await new Promise(
(done, error) => ((socketWeb.onopen = done), (socketWeb.onerror = error))
);
const socketTCP = createConnection(8884, "127.0.0.1");
await new Promise(done => socketTCP.on("connect", done));
const messages: string[] = [];
let callback: (e: void) => void;
socketWeb.onmessage = arg => {
messages.push(arg.data.toString("utf8"));
if (callback) callback();
};
const waitForMessage = async () => {
if (messages.length === 0) {
await new Promise(done => (callback = done));
}
return messages.shift();
};
await new Promise(done =>
socketTCP.write("something\nsecond line\nbegin", done)
);
expect(await waitForMessage()).toEqual("something");
expect(await waitForMessage()).toEqual("second line");
await new Promise(done => socketTCP.write(" end\n", done));
expect(await waitForMessage()).toEqual("begin end");
await new Promise(done => socketTCP.write("other text\n", done));
expect(await waitForMessage()).toEqual("other text");
await new Promise<void>(done => socketTCP.end(done));
socketWeb.close();
await new Promise(done => (socketWeb.onclose = done));
});
it("should not accept cross-origin websocket connections", async () => {
const socketWeb = new Websocket("ws://127.0.0.1:8883/screen-reader", {
origin: "http://example.com"
});
await expect(
new Promise(
(done, error) => (
(socketWeb.onopen = done), (socketWeb.onerror = error)
)
)
).rejects.toBeTruthy();
});
it("should not accept cross-origin POST requests", async () => {
const request = await fetch("http://127.0.0.1:8883/browser", {
method: "POST",
headers: {
Origin: "http://example.com"
},
body: JSON.stringify({ options: {}, browser: "chromium" })
});
expect(request.status).toBe(403);
expect(request.ok).toBeFalsy();
});
it("should not accept cross-origin DELETE requests", async () => {
const request = await fetch(
"http://127.0.0.1:8883/browser/1234567890123456789012345678901234567890123456789012345678901234",
{
method: "DELETE",
headers: {
Origin: "http://example.com"
}
}
);
expect(request.status).toBe(403);
expect(request.ok).toBeFalsy();
});
it("should return 404 for DELETE requests not matching an instance", async () => {
const request = await fetch(
"http://127.0.0.1:8883/browser/1234567890123456789012345678901234567890123456789012345678901234",
{
method: "DELETE"
}
);
expect(request.status).toBe(404);
expect(request.ok).toBeFalsy();
});
it("should accept POST and DELETE requests to create and delete browser instances", async () => {
const postRequest = await fetch("http://127.0.0.1:8883/browser", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ options: {}, browser: "chromium" })
});
expect(postRequest.ok).toBeTruthy();
const { id } = (await postRequest.json()) as any;
expect(id).toMatch(/^[0-9a-f]{64}$/i);
const deleteRequest = await fetch(`http://127.0.0.1:8883/browser/${id}`, {
method: "DELETE"
});
expect(deleteRequest.status).toBe(200);
expect(deleteRequest.ok).toBeTruthy();
}, 30000);
const checkInvalid = async (object: any, error: string) => {
const postRequest = await fetch("http://127.0.0.1:8883/browser", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(object)
});
expect(postRequest.ok).toBeFalsy();
expect(postRequest.status).toBe(400);
const json = await postRequest.text();
expect(json).toContain(error);
};
it("should validate POST requests to create a browser instances", async () => {
await checkInvalid({}, "must have required property 'browser'");
await checkInvalid(
{ browser: "unknown", options: {} },
"must be equal to one of the allowed values"
);
await checkInvalid(
{ browser: "firefox", options: {}, extraOption: {} },
"must NOT have additional properties"
);
await checkInvalid(
{ browser: "firefox", options: { invalidExtraProperty: "ok" } },
"must NOT have additional properties"
);
});
});
Example #3
Source File: listener.ts From hoprnet with GNU General Public License v3.0 | 4 votes |
async isExposedHost(
externalIp: string,
port: number
): Promise<{
udpMapped: boolean
tcpMapped: boolean
}> {
const UDP_TEST = new TextEncoder().encode('TEST_UDP')
const TCP_TEST = new TextEncoder().encode('TEST_TCP')
const waitForIncomingUdpPacket = defer<void>()
const waitForIncomingTcpPacket = defer<void>()
const TIMEOUT = 500
const abort = new AbortController()
const tcpTimeout = setTimeout(() => {
abort.abort()
waitForIncomingTcpPacket.reject()
}, TIMEOUT)
const udpTimeout = setTimeout(waitForIncomingUdpPacket.reject.bind(waitForIncomingUdpPacket), TIMEOUT)
const checkTcpMessage = (socket: TCPSocket) => {
socket.on('data', (data: Buffer) => {
if (u8aEquals(data, TCP_TEST)) {
clearTimeout(tcpTimeout)
waitForIncomingTcpPacket.resolve()
}
})
}
this.tcpSocket.on('connection', checkTcpMessage)
const checkUdpMessage = (msg: Buffer) => {
if (u8aEquals(msg, UDP_TEST)) {
clearTimeout(udpTimeout)
waitForIncomingUdpPacket.resolve()
}
}
this.udpSocket.on('message', checkUdpMessage)
const secondUdpSocket = createSocket('udp4')
secondUdpSocket.send(UDP_TEST, port, externalIp)
let done = false
const cleanUp = (): void => {
if (done) {
return
}
done = true
clearTimeout(tcpTimeout)
clearTimeout(udpTimeout)
this.udpSocket.removeListener('message', checkUdpMessage)
this.tcpSocket.removeListener('connection', checkTcpMessage)
tcpSocket.destroy()
secondUdpSocket.close()
}
const tcpSocket = createConnection({
port,
host: externalIp,
signal: abort.signal
})
.on('connect', () => {
tcpSocket.write(TCP_TEST, (err: any) => {
if (err) {
log(`Failed to send TCP packet`, err)
}
})
})
.on('error', (err: any) => {
if (err && (err.code == undefined || err.code !== 'ABORT_ERR')) {
error(`Error while checking NAT situation`, err.message)
}
})
if (!done) {
const results = await Promise.allSettled([waitForIncomingUdpPacket.promise, waitForIncomingTcpPacket.promise])
cleanUp()
return {
udpMapped: results[0].status === 'fulfilled',
tcpMapped: results[1].status === 'fulfilled'
}
}
return {
udpMapped: false,
tcpMapped: false
}
}
Example #4
Source File: runForwardingServer.ts From shroom with GNU Lesser General Public License v3.0 | 4 votes |
export function runForwardingServer({
wsPort,
targetPort,
debug = false,
prependLengthPrefix = false,
targetHost,
keyPath,
certPath
}: {
wsPort: number;
targetPort: number;
debug?: boolean;
targetHost?: string;
prependLengthPrefix?: boolean;
keyPath?: string,
certPath?: string,
}) {
let webSocketOptions: WebSocket.ServerOptions;
if (keyPath && certPath) {
webSocketOptions = {
server: createServer({
key: readFileSync(keyPath),
cert: readFileSync(certPath)
})
};
webSocketOptions.server?.listen(wsPort);
} else {
webSocketOptions = {
port: wsPort
};
}
const server = new WebSocket.Server(webSocketOptions);
const targetHostStr =
targetHost == null ? `:${targetPort}` : `${targetHost}:${targetPort}`;
console.log(
`${webSocketOptions.server ? 'Secure' : ''} WebSocket Server started on port ${wsPort}. Forwarding traffic to ${targetHostStr}.`
);
let idCounter = 0;
server.on("connection", (ws) => {
const id = ++idCounter;
if (debug) console.log(`[${id}] Forwarding WebSocket Client connection`);
// When a websocket client connects, create a socket to the emulator server
const connection = createConnection({ port: targetPort, host: targetHost });
// Pipe to the frame-stream decoder to handle length prefixed messages
connection.pipe(frame.decode()).on("data", (buffer: Buffer) => {
if (prependLengthPrefix) {
const framedBuffer: any = buffer;
const baseBuffer = new ByteBuffer();
baseBuffer.writeInt(framedBuffer.frameLength);
baseBuffer.append(buffer);
ws.send(baseBuffer.flip().toBuffer());
} else {
ws.send(buffer);
}
if (debug) console.log(`[${id}] Server => Client:`, buffer);
});
// Forward close event from server to websocket client
connection.on("close", () => {
ws.close();
if (debug) console.log(`[${id}] Server closed the connection`);
});
// Forward messages sent by the websocket client to the emulator server
ws.on("message", (message) => {
const buffer = message as Buffer;
const data = new ByteBuffer();
// Write an int to the payload with the size of the buffer we are sending
data.writeInt(buffer.length);
data.append(buffer);
const sendBuffer = data.flip().toBuffer();
connection.write(sendBuffer);
if (debug) console.log(`[${id}] Client => Server:`, sendBuffer);
});
// Forward close event to the emulator server
ws.on("close", () => {
connection.end();
if (debug) console.log(`[${id}] WebSocket closed the connection`);
});
});
return {
close() {
server.close();
},
};
}