Spaces:
Sleeping
Sleeping
Update app.js
Browse files
app.js
CHANGED
|
@@ -1,21 +1,54 @@
|
|
| 1 |
const express = require('express');
|
| 2 |
const app = express();
|
|
|
|
|
|
|
| 3 |
|
| 4 |
-
//
|
| 5 |
-
|
| 6 |
|
| 7 |
-
app.
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
-
|
| 13 |
-
console.log("Received JSON:", req.body);
|
| 14 |
-
res.json({ status: "success", message: "Data received" });
|
| 15 |
});
|
| 16 |
|
| 17 |
-
//
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
});
|
|
|
|
|
|
|
|
|
| 1 |
const express = require('express');
|
| 2 |
const app = express();
|
| 3 |
+
const bodyParser = require('body-parser');
|
| 4 |
+
const webrtc = require('wrtc');
|
| 5 |
|
| 6 |
+
// Instead of one global stream, keep one per room
|
| 7 |
+
const roomStreams = {}; // { [roomId]: MediaStream }
|
| 8 |
|
| 9 |
+
app.use(express.static('public'));
|
| 10 |
+
app.use(bodyParser.json());
|
| 11 |
+
app.use(bodyParser.urlencoded({ extended: true }));
|
| 12 |
+
|
| 13 |
+
// Consumer endpoint: front-end must POST { sdp, roomId }
|
| 14 |
+
app.post("/consumer", async ({ body }, res) => {
|
| 15 |
+
const { sdp, roomId } = body;
|
| 16 |
+
const stream = roomStreams[roomId];
|
| 17 |
+
if (!stream) {
|
| 18 |
+
return res.status(404).json({ error: "No broadcast for room " + roomId });
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
const peer = new webrtc.RTCPeerConnection({
|
| 22 |
+
iceServers: [{ urls: "stun:stun.stunprotocol.org" }]
|
| 23 |
+
});
|
| 24 |
+
|
| 25 |
+
// add the broadcaster’s tracks for this room
|
| 26 |
+
stream.getTracks().forEach(track => peer.addTrack(track, stream));
|
| 27 |
+
|
| 28 |
+
await peer.setRemoteDescription(new webrtc.RTCSessionDescription(sdp));
|
| 29 |
+
const answer = await peer.createAnswer();
|
| 30 |
+
await peer.setLocalDescription(answer);
|
| 31 |
|
| 32 |
+
res.json({ sdp: peer.localDescription });
|
|
|
|
|
|
|
| 33 |
});
|
| 34 |
|
| 35 |
+
// Broadcast endpoint: front-end must POST { sdp, roomId }
|
| 36 |
+
app.post("/broadcast", async ({ body }, res) => {
|
| 37 |
+
const { sdp, roomId } = body;
|
| 38 |
+
const peer = new webrtc.RTCPeerConnection({
|
| 39 |
+
iceServers: [{ urls: "stun:stun.stunprotocol.org" }]
|
| 40 |
+
});
|
| 41 |
+
|
| 42 |
+
peer.ontrack = ({ streams }) => {
|
| 43 |
+
// store the incoming stream under its roomId
|
| 44 |
+
roomStreams[roomId] = streams[0];
|
| 45 |
+
};
|
| 46 |
+
|
| 47 |
+
await peer.setRemoteDescription(new webrtc.RTCSessionDescription(sdp));
|
| 48 |
+
const answer = await peer.createAnswer();
|
| 49 |
+
await peer.setLocalDescription(answer);
|
| 50 |
+
|
| 51 |
+
res.json({ sdp: peer.localDescription });
|
| 52 |
});
|
| 53 |
+
|
| 54 |
+
app.listen(5000, () => console.log('SFU server running on port 5000'));
|