Skip to content

Commit

Permalink
Merge pull request #273 from murat-dogan/websocket-examples
Browse files Browse the repository at this point in the history
Convert ws to Native WebSockets
  • Loading branch information
murat-dogan authored Jul 23, 2024
2 parents aa01a37 + e5d386a commit acbd595
Show file tree
Hide file tree
Showing 10 changed files with 106 additions and 103 deletions.
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);
}
}
24 changes: 1 addition & 23 deletions test/connectivity.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,16 @@
import nodeDataChannel from '../lib/index.js';

nodeDataChannel.initLogger('Debug');
nodeDataChannel.preload();

let dc1 = null;
let dc2 = null;

// Config options
// export interface RtcConfig {
// iceServers: string[];
// proxyServer?: ProxyServer;
// bindAddress?: string;
// enableIceTcp?: boolean;
// portRangeBegin?: number;
// portRangeEnd?: number;
// maxMessageSize?: number;
// iceTransportPolicy?: TransportPolicy;
// }
//
// "iceServers" option is an array of stun/turn server urls
// Examples;
// STUN Server Example : stun:stun.l.google.com:19302
// TURN Server Example : turn:USERNAME:PASSWORD@TURN_IP_OR_ADDRESS:PORT
// TURN Server Example (TCP) : turn:USERNAME:PASSWORD@TURN_IP_OR_ADDRESS:PORT?transport=tcp
// TURN Server Example (TLS) : turns:USERNAME:PASSWORD@TURN_IP_OR_ADDRESS:PORT

let peer1 = new nodeDataChannel.PeerConnection('Peer1', { iceServers: ['stun:stun.l.google.com:19302'] });

// Set Callbacks
Expand Down Expand Up @@ -78,15 +64,7 @@ peer2.onDataChannel((dc) => {
});
});

// DataChannel Options
// export interface DataChannelInitConfig {
// protocol?: string;
// negotiated?: boolean;
// id?: number;
// ordered?: boolean;
// maxPacketLifeTime?: number;
// maxRetransmits?: number;
// }
// Create DataChannel
dc1 = peer1.createDataChannel('test');
dc1.onOpen(() => {
dc1.sendMessage('Hello from Peer1');
Expand Down

0 comments on commit acbd595

Please sign in to comment.