我正在尝试通过 webrtc 数据通道发送数据。下面是我的代码
//client-side code
// Connect to the WebSocket server
var ID = null;
const ws = new WebSocket("ws://localhost:8080");
// Setting up peer connection (UDP)
const localConnection = new RTCPeerConnection();
const dataChannel = localConnection.createDataChannel("sendChannel");
document.getElementById("Send").addEventListener('click' , function(){
console.log("Try to sending essage...");
dataChannel.send("Helllo")
})
// console.log(Object.getPrototypeOf(ws));
ws.onopen = () => {
console.log("Connected to server");
//const dataChannel = connection.createDataChannel("channel");
localConnection.onicecandidate = (e) => {
console.log("New ICE Candidate!" , localConnection.localDescription.type);
ws.send(JSON.stringify({
type: "create"+ localConnection.localDescription.type,
data: {
id: ID,
sdp: localConnection.localDescription
}
}))
/* ws.send(JSON.stringify({
type: "ICE",
data: {
sdp: localConnection.localDescription
}
}));*/
//ws.send("[Server]:New Ice candidate");
};
localConnection.onicecandidateerror = (e) => {
console.warn("Error: ICE Candidate", e);
};
dataChannel.onmessage = (e) =>
console.log("messsage received!!!" + e.data);
dataChannel.onopen = (e) => console.log("open!!!!");
dataChannel.onclose = (e) => console.log("closed!!!!!!");
// Send a message to the server
ws.send(JSON.stringify({type: "findLobby" , "message": null}));
};
ws.onclose = () => {
console.log("Disconnected from server");
};
ws.onmessage = (event) => {
// console.log(Received message from server: ${typeof event.data});
//if (typeof event.data !== "object") return;
var data = JSON.parse(event.data);
switch (data.type) {
case "createOffer":
console.log("Creating Offer!");
localConnection.createOffer()
.then(o => {
//console.log(o);
localConnection.setLocalDescription(o);
/* ws.send(JSON.stringify({
type: "createOffer",
data: {
sdp: o
}
}))*/
});
break;
case "createAnswer":
console.log("reating Answer!");
console.log("Public session Found: Your are now joining...");
localConnection.setRemoteDescription(data.data[1].sdp).then(a=> console.log(localConnection.remoteDescription, "Remote connection setup"))
localConnection.createAnswer().then(a=>{
console.log(a)
localConnection.setLocalDescription(a).then(()=> {
console.log('Local description is setup: ',localConnection.localDescription)
ws.send(JSON.stringify({
type: "answer",
data: {
sessionid: data.data[0],
sdp: localConnection.localDescription
}
}))
});
});
break;
case "acceptAnswer":
console.log("Accept Answer: ",event.data)
let datax = JSON.parse(event.data);
let answer = datax.data.sdp;
localConnection.setRemoteDescription(answer).then(a => {
console.log("establishing connection...");
//dataChannel.send(JSON.stringify({message: "Hello" , data: datax}))
})
break;
case "message":
console.log(event.data)
break;
case "newclient":
console.log("New client id" , event.data);
ID = JSON.parse(event.data).id;
break;
default:
console.log("Invalid Type");
break;
}
};
服务器端代码(websocket)
const WebSocket = require('ws');
// Create a WebSocket server listening on port 8080
const wss = new WebSocket.Server({ port: 8080 });
const freeUsers = new Map();
const connected = [];
const clients = new Map();
class PublicLobby{
constructor(id){
this.id = id;
this.players = new Map();
this.host = null;
}
}
wss.on('connection', (ws) => {
var sessionid = generateUniqueId();
clients.set(sessionid , {
isJoined: false,
isFree: true,
ws: ws,
});
// Send a welcome message to the client
ws.send(JSON.stringify(
{
type: 'newclient',
id: sessionid,
}
))
ws.send(JSON.stringify({type: 'message' , message: 'Welcome to the WebSocket server!'}));
// Listen for messages from the client
ws.on('message', (message) => {
let m = JSON.parse(message);
console.log("Free Users:" , freeUsers);
//console.log("clients:" , clients);
switch (m.type) {
case "createoffer":
if(clients.has(m.data.id)){
let player = clients.get(m.data.id)
player.sdp = m.data.sdp;
if(freeUsers.has(m.data.id)){
freeUsers.get(m.data.id).sdp = m.data.sdp;
}
else{
freeUsers.set(m.data.id , {
isJoined: false,
isFree: true,
ws: player.ws,
...m.data});
ws.send(JSON.stringify({type: "message" , message: "New Session has been created!" }));
}
}
break;
case "ICE":
// console.log("Ice data:" , m.data);
ws.send(JSON.stringify({type: "acceptAnswer" , message: "Ice answer" , data: m.data}))
break;
case "createanswer":
//console.log(m.data);
const freeUser = freeUsers.entries().next().value;
if (freeUser && !freeUser[1].ans) {
freeUser[1].ws.send(JSON.stringify({ type: "acceptAnswer", message: "Answer from client", data: m.data }));
freeUser[1].ans = true;
}
break;
case "findLobby":
if(freeUsers.size > 0)
ws.send(JSON.stringify({ type: "createAnswer", message:"Lobby Found you are joining now.." , data: freeUsers.entries().next().value}));
else
ws.send(JSON.stringify({ type: "createOffer", message:"No Session founnd (creating a new public session...)"}))
break;
default:
break;
}
});
// Handle client disconnection
ws.on('close', () => {
// freeUsers.get()
console.log('Client disconnected');
});
});
function generateUniqueId() {
return `session_${Math.random().toString(36).substr(2, 9)}`;
}
console.log('WebSocket server is running on ws://localhost:8080');
我正在尝试通过 WEBRTC 数据通道发送数据以进行简单的多人游戏。
datachannel
已成功打开,但是当我尝试通过它发送消息时没有任何反应。
控制台中没有显示任何错误。
不确定我的代码有什么问题。
请帮助我。谢谢
消息实际发送和接收(可以在数据通道统计中的 chrome://webrtc-internals 中看到)。
但是您正在创建两个具有相同名称的通道,连接的每一侧各一个,并且没有按照
的方式添加消息侦听器let receiveChannel;
localConnection.ondatachannel = e => {
console.log('channel event', e);
receiveChannel = e.channel;
receiveChannel.onmessage = (e) => console.log('received', e.data, e);
}