Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Convert ws to Native WebSockets #273

Merged
merged 6 commits into from
Jul 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 7 additions & 9 deletions examples/client-server/client-benchmark.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ const require = createRequire(import.meta.url);
const yargs = require('yargs/yargs');
const { hideBin } = require('yargs/helpers');

import WebSocket from 'ws';
import readline from 'readline';
import nodeDataChannel from '../../lib/index.js';

Expand Down Expand Up @@ -60,23 +59,22 @@ const rl = readline.createInterface({
output: process.stdout,
});

const ws = new WebSocket(wsUrl + '/' + id, {
perMessageDeflate: false,
});
const ws = new nodeDataChannel.WebSocket();
ws.open(wsUrl + '/' + id);

console.log(`The local ID is: ${id}`);
console.log(`Waiting for signaling to be connected...`);

ws.on('open', () => {
ws.onOpen(() => {
console.log('WebSocket connected, signaling ready');
readUserInput();
});

ws.on('error', (err) => {
ws.onError((err) => {
console.log('WebSocket Error: ', err);
});

ws.on('message', (msgStr) => {
ws.onMessage((msgStr) => {
let msg = JSON.parse(msgStr);
switch (msg.type) {
case 'offer':
Expand Down Expand Up @@ -184,10 +182,10 @@ function createPeerConnection(peerId) {
console.log('GatheringState: ', state);
});
peerConnection.onLocalDescription((description, type) => {
ws.send(JSON.stringify({ id: peerId, type, description }));
ws.sendMessage(JSON.stringify({ id: peerId, type, description }));
});
peerConnection.onLocalCandidate((candidate, mid) => {
ws.send(JSON.stringify({ id: peerId, type: 'candidate', candidate, mid }));
ws.sendMessage(JSON.stringify({ id: peerId, type: 'candidate', candidate, mid }));
});
peerConnection.onDataChannel((dc) => {
rl.close();
Expand Down
16 changes: 7 additions & 9 deletions examples/client-server/client-periodic.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import WebSocket from 'ws';
import readline from 'readline';
import nodeDataChannel from '../../lib/index.js';

Expand All @@ -25,23 +24,22 @@ const rl = readline.createInterface({

// Signaling Server
const WS_URL = process.env.WS_URL || 'ws://localhost:8000';
const ws = new WebSocket(WS_URL + '/' + id, {
perMessageDeflate: false,
});
const ws = new nodeDataChannel.WebSocket();
ws.open(WS_URL + '/' + id);

console.log(`The local ID is: ${id}`);
console.log(`Waiting for signaling to be connected...`);

ws.on('open', () => {
ws.onOpen(() => {
console.log('WebSocket connected, signaling ready');
readUserInput();
});

ws.on('error', (err) => {
ws.onError((err) => {
console.log('WebSocket Error: ', err);
});

ws.on('message', (msgStr) => {
ws.onMessage((msgStr) => {
let msg = JSON.parse(msgStr);
switch (msg.type) {
case 'offer':
Expand Down Expand Up @@ -122,10 +120,10 @@ function createPeerConnection(peerId) {
console.log('GatheringState: ', state);
});
peerConnection.onLocalDescription((description, type) => {
ws.send(JSON.stringify({ id: peerId, type, description }));
ws.sendMessage(JSON.stringify({ id: peerId, type, description }));
});
peerConnection.onLocalCandidate((candidate, mid) => {
ws.send(JSON.stringify({ id: peerId, type: 'candidate', candidate, mid }));
ws.sendMessage(JSON.stringify({ id: peerId, type: 'candidate', candidate, mid }));
});
peerConnection.onDataChannel((dc) => {
rl.close();
Expand Down
16 changes: 7 additions & 9 deletions examples/client-server/client.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import WebSocket from 'ws';
import readline from 'readline';
import nodeDataChannel from '../../lib/index.js';

Expand All @@ -13,23 +12,22 @@ const id = randomId(4);

// Signaling Server
const WS_URL = process.env.WS_URL || 'ws://localhost:8000';
const ws = new WebSocket(WS_URL + '/' + id, {
perMessageDeflate: false,
});
const ws = new nodeDataChannel.WebSocket();
ws.open(WS_URL + '/' + id);

console.log(`The local ID is: ${id}`);
console.log(`Waiting for signaling to be connected...`);

ws.on('open', () => {
ws.onOpen(() => {
console.log('WebSocket connected, signaling ready');
readUserInput();
});

ws.on('error', (err) => {
ws.onError((err) => {
console.log('WebSocket Error: ', err);
});

ws.on('message', (msgStr) => {
ws.onMessage((msgStr) => {
let msg = JSON.parse(msgStr);
switch (msg.type) {
case 'offer':
Expand Down Expand Up @@ -86,10 +84,10 @@ function createPeerConnection(peerId) {
console.log('GatheringState: ', state);
});
peerConnection.onLocalDescription((description, type) => {
ws.send(JSON.stringify({ id: peerId, type, description }));
ws.sendMessage(JSON.stringify({ id: peerId, type, description }));
});
peerConnection.onLocalCandidate((candidate, mid) => {
ws.send(JSON.stringify({ id: peerId, type: 'candidate', candidate, mid }));
ws.sendMessage(JSON.stringify({ id: peerId, type: 'candidate', candidate, mid }));
});
peerConnection.onDataChannel((dc) => {
console.log('DataChannel from ' + peerId + ' received with label "', dc.getLabel() + '"');
Expand Down
27 changes: 0 additions & 27 deletions examples/client-server/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion examples/client-server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
"author": "",
"license": "ISC",
"dependencies": {
"ws": "^7.5.3",
"yargs": "^16.2.0"
}
}
31 changes: 21 additions & 10 deletions examples/client-server/signaling-server.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,22 @@
import WebSocket from 'ws';
import nodeDataChannel from '../../lib/index.js';

// Init Logger
nodeDataChannel.initLogger('Debug');

const clients = {};

const wss = new WebSocket.Server({ port: 8000 });
const wsServer = new nodeDataChannel.WebSocketServer({ bindAddress: '127.0.0.1', port: 8000 });

wsServer.onClient((ws) => {
let id = '';

wss.on('connection', (ws, req) => {
const id = req.url.replace('/', '');
console.log(`New Connection from ${id}`);
ws.onOpen(() => {
id = ws.path().replace('/', '');
console.log(`New Connection from ${id}`);
clients[id] = ws;
});

clients[id] = ws;
ws.on('message', (buffer) => {
ws.onMessage((buffer) => {
let msg = JSON.parse(buffer);
let peerId = msg.id;
let peerWs = clients[peerId];
Expand All @@ -18,11 +25,15 @@ wss.on('connection', (ws, req) => {
if (!peerWs) return console.error(`Can not find peer with ID ${peerId}`);

msg.id = id;
peerWs.send(JSON.stringify(msg));
peerWs.sendMessage(JSON.stringify(msg));
});

ws.on('close', () => {
console.log(`${id} disconected`);
ws.onClosed(() => {
console.log(`${id} disconnected`);
delete clients[id];
});

ws.onError((err) => {
console.error(err);
});
});
37 changes: 22 additions & 15 deletions lib/index.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
// createRequire is native in node version >= 12
import { createRequire } from 'module';
const require = createRequire(import.meta.url);

const nodeDataChannel = require('../build/Release/node_datachannel.node');
import nodeDataChannel from './node-datachannel.js';
import DataChannelStream from './datachannel-stream.js';
import WebSocketServer from './websocket-server.js';

const {
initLogger,
Expand All @@ -17,9 +14,16 @@ const {
DataChannel,
PeerConnection,
WebSocket,
WebSocketServer,
} = nodeDataChannel;

export const DescriptionType = {
Unspec: 'unspec',
Offer: 'offer',
Answer: 'answer',
Pranswer: 'pranswer',
Rollback: 'rollback',
};

export {
initLogger,
cleanup,
Expand All @@ -38,14 +42,17 @@ export {
};

export default {
...nodeDataChannel,
initLogger,
cleanup,
preload,
setSctpSettings,
RtcpReceivingSession,
Track,
Video,
Audio,
DataChannel,
PeerConnection,
WebSocket,
WebSocketServer,
DataChannelStream,
};

export const DescriptionType = {
Unspec: 'unspec',
Offer: 'offer',
Answer: 'answer',
Pranswer: 'pranswer',
Rollback: 'rollback',
};
7 changes: 7 additions & 0 deletions lib/node-datachannel.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// createRequire is native in node version >= 12
import { createRequire } from 'module';
const require = createRequire(import.meta.url);

const nodeDataChannel = require('../build/Release/node_datachannel.node');

export default nodeDataChannel;
34 changes: 34 additions & 0 deletions lib/websocket-server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { EventEmitter } from 'events';
import nodeDataChannel from './node-datachannel.js';

export default class WebSocketServer extends EventEmitter {
#server;
#clients = [];

constructor(options) {
super();
this.#server = new nodeDataChannel.WebSocketServer(options);

this.#server.onClient((client) => {
this.emit('client', client);
this.#clients.push(client);
});
}

port() {
return this.#server?.port() || 0;
}

stop() {
this.#clients.forEach((client) => {
client?.close();
});
this.#server?.stop();
this.#server = null;
this.removeAllListeners();
}

onClient(cb) {
if (this.#server) this.on('client', cb);
}
}
Loading
Loading