跳到主要内容

web rtc 网速

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebRTC Speed Test</title>
</head>
<body>
<h1>WebRTC Speed Test</h1>
<button id="startButton">Start Test</button>
<p id="status">Status: Not started</p>
<p id="speed">Speed: N/A</p>

<script>
const startButton = document.getElementById('startButton');
const statusText = document.getElementById('status');
const speedText = document.getElementById('speed');

startButton.addEventListener('click', startTest);

let peerConnection;
let dataChannel;

function startTest() {
statusText.textContent = 'Status: Starting...';

const config = {
iceServers: []
};
peerConnection = new RTCPeerConnection(config);

// Create a data channel
dataChannel = peerConnection.createDataChannel('speedTest');
dataChannel.onopen = onDataChannelOpen;
dataChannel.onmessage = onDataChannelMessage;

// Create an offer
peerConnection.createOffer().then(offer => {
return peerConnection.setLocalDescription(offer);
}).then(() => {
// Simulate signaling by directly setting the remote description
const remoteDescription = new RTCSessionDescription(peerConnection.localDescription);
return peerConnection.setRemoteDescription(remoteDescription);
}).catch(error => {
console.error('Error creating offer:', error);
statusText.textContent = 'Status: Error';
});
}

function onDataChannelOpen() {
statusText.textContent = 'Status: Data channel open';

const data = new Uint8Array(1000000); // 1 MB of data
const startTime = Date.now();

dataChannel.send(data);

dataChannel.onmessage = () => {
const endTime = Date.now();
const duration = (endTime - startTime) / 1000; // Time in seconds
const sizeInBits = data.length * 8;
const speedInBps = sizeInBits / duration; // Speed in bits per second
const speedInMbps = speedInBps / (1024 * 1024); // Convert to Mbps

speedText.textContent = `Speed: ${speedInMbps.toFixed(2)} Mbps`;
statusText.textContent = 'Status: Test complete';
};
}

function onDataChannelMessage(event) {
console.log('Received message:', event.data);
}
</script>
</body>
</html>