I am trying to send data through webrtc datachannel. Below is the my code
//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;
}
};
Server Side code (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');
I am trying to sending data through WEBRTC data-channel for simple multiplayer game. The datachannel
is successfully opened but when i try to send a message through it nothing happens.
No errors were displayed in console.
not sure what is wrong with my code.
Please Help me.thanks
The message is actually sent and received (you can see that in chrome://webrtc-internals in the datachannel statistics).
But you are creating two channels with the same name, one of each side of the connection and not adding a message listener along the lines of
let receiveChannel;
localConnection.ondatachannel = e => {
console.log('channel event', e);
receiveChannel = e.channel;
receiveChannel.onmessage = (e) => console.log('received', e.data, e);
}