我正在开发一个基于网络的应用程序,其目标是在同一 wifi 连接上的设备之间共享文件。我是一名 javascript 开发人员,但我从未使用过连接技术。有没有办法使用 javascript/jquery 或任何其他 API 来做到这一点?
我只知道网络信息API,它返回连接类型信息以及其他一些信息。到目前为止,我只能检查连接类型和速度。
var connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
if (connection) {
var connection_type=connection.type;
var effectivetype=connection.effectiveType;
var downSpeed = connection.downlink;
console.log('download speed'+downSpeed +'effectivetype:'+effectivetype'+
Connection type:'+connection_type);
}
var connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
if (connection) {
var connection_type=connection.type;
if (connection_type=='wifi') {
//the device is connected to a wifi
var wifi_name = 'mywifi';
if (wifi_name == 'mywifi') {
//device is connected to my wifi
var create_connection = create a connection();
if (create_connection) {
//a connection is created between two devices
send_file();
//send a file
}
}
}
}
我正在使用 webRTC 和网络套接字做类似的事情
function connectWebSocket() {
websocket = new WebSocket("ws://localhost:8080");
websocket.onopen = () => console.log("Connected to WebSocket server");
websocket.onmessage = (event) => handleSignalingMessage(JSON.parse(event.data));
}
registerBtn.onclick = () => {
const username = usernameInput.value.trim();
if (!username) {
alert("Enter a username!");
return;
}
websocket.send(JSON.stringify({ type: "register", username }));
console.log(`Registered as ${username}`);
};
callBtn.onclick = async () => {
const targetUsername = targetUsernameInput.value.trim();
if (!targetUsername) {
alert("Enter a target username!");
return;
}
// Create PeerConnection
localConnection = createPeerConnection(targetUsername);
// Create DataChannel
dataChannel = localConnection.createDataChannel("fileTransfer");
dataChannel.onopen = () => {
console.log("DataChannel open!");
sendFileBtn.disabled = false; // Enable file send button when DataChannel is open
};
dataChannel.onmessage = (event) => receiveFile(event.data);
// Create and send offer
const offer = await localConnection.createOffer();
await localConnection.setLocalDescription(offer);
websocket.send(
JSON.stringify({
type: "offer",
offer,
target: targetUsername,
})
);
};
function handleSignalingMessage(message) {
switch (message.type) {
case "offer":
handleOffer(message.offer, message.target);
break;
case "answer":
handleAnswer(message.answer);
break;
case "candidate":
handleCandidate(message.candidate);
break;
default:
console.log("Unknown signaling message:", message);
}
}
async function handleOffer(offer, target) {
// Ensure the remote connection is created before handling the offer
if (!remoteConnection) {
remoteConnection = createPeerConnection(target);
}
await remoteConnection.setRemoteDescription(new RTCSessionDescription(offer));
const answer = await remoteConnection.createAnswer();
await remoteConnection.setLocalDescription(answer);
websocket.send(
JSON.stringify({
type: "answer",
answer,
target,
})
);
}
function handleAnswer(answer) {
if (!localConnection) {
console.error("Local connection is not initialized yet");
return;
}
localConnection.setRemoteDescription(new RTCSessionDescription(answer));
console.log("Connection established!");
}
function handleCandidate(candidate) {
// ICE candidates must only be added after remote description is set
if (!localConnection || !remoteConnection) {
console.log("Waiting for peer connection setup before adding ICE candidate.");
return;
}
const conn = localConnection || remoteConnection;
conn.addIceCandidate(new RTCIceCandidate(candidate));
}
function createPeerConnection(target) {
const connection = new RTCPeerConnection();
connection.onicecandidate = (event) => {
if (event.candidate) {
websocket.send(
JSON.stringify({
type: "candidate",
candidate: event.candidate,
target,
})
);
}
};
connection.ondatachannel = (event) => {
receiveChannel = event.channel;
receiveChannel.onmessage = (event) => receiveFile(event.data);
};
return connection;
}
sendFileBtn.onclick = () => {
const file = fileInput.files[0];
if (!file || !dataChannel) {
alert("Select a file and establish a connection first!");
return;
}
// Ensure the DataChannel is open before sending
if (dataChannel.readyState === "open") {
const reader = new FileReader();
reader.onload = (event) => {
dataChannel.send(event.target.result);
console.log(`File sent: ${file.name}`);
};
reader.readAsArrayBuffer(file);
} else {
console.log("DataChannel is not open yet, waiting...");
}
};
// Receive File
function receiveFile(fileData) {
const blob = new Blob([fileData]);
const url = URL.createObjectURL(blob);
downloadLink.href = url;
downloadLink.style.display = "block";
downloadLink.textContent = "Download Received File";
console.log("File received!");
}
connectWebSocket();
const WebSocket = require('ws');
const wss = new WebSocket.Server({ 端口: 8080 });
让客户 = {};
wss.on('连接', (ws) => { console.log('新客户端已连接');
ws.on('message', (message) => {
const data = JSON.parse(message);
switch (data.type) {
case 'register':
clients[data.username] = ws;
console.log(`Registered: ${data.username}`);
break;
case 'offer':
case 'answer':
case 'candidate':
if (clients[data.target]) {
clients[data.target].send(JSON.stringify(data));
}
break;
default:
console.log('Unknown message type:', data.type);
}
});
ws.on('close', () => {
Object.keys(clients).forEach((username) => {
if (clients[username] === ws) {
console.log(`${username} disconnected`);
delete clients[username];
}
});
});
});
console.log('在 ws://localhost:8080 上运行的 WebSocket 服务器');
我发现这个网页提供了您需要的东西,请查看:www.bridgefy.me