使用WebRTC做的视频聊天项目,后端使用node。
使用方式 把 前端文件放在RTCDom文件夹内,这个文件夹放在跟webSocket.js同级下。
用node运行webSocket.js 浏览器打开 https:+本机端口号+8081端口 即可。
登录方式 用户名随便写 密码为 aabbcc。
需要安装node的几个包
wss,ws
index.html 登录页
<!doctype html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>视频会议</title>
<link rel="stylesheet" type="text/css" href="css/styles.css">
</head>
<body>
<div class="htmleaf-container">
<div class="wrapper">
<div class="container">
<h1>视频会议</h1>
<form class="form" name="user">
<input name="userName" type="text" placeholder="Username">
<input name="password" type="password" placeholder="Password">
<button type="submit" id="login-button">Login</button>
</form>
</div>
<ul class="bg-bubbles">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
</div>
<script src="js/jquery-2.1.1.min.js" type="text/javascript"></script>
<script>
$('#login-button').click(function (event) {
user=new Object();
var form= document.user;
user.name=form.getElementsByTagName("input")[0].value;
user.password=form.getElementsByTagName("input")[1].value;
if(user.name&&user.password=="aabbcc"){
event.preventDefault();
$('form').fadeOut(500);
$('.wrapper').addClass('form-success');
var userStr=JSON.stringify(user);
window.location.href="newWS.html?user="+userStr;
}else{
alert("账户名或密码不正确");
}
});
</script>
</body>
</html>
newWS视频会议页面
<!DOCTYPE html>
<!--
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> -->
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Learning WebRTC - Chapter 5: Connecting ClientsTogether</title>
<style>
body {
background-color: #009688;
margin-top: 15px;
font-family: sans-serif;
color: white;
margin: 0px;
}
video {
background: black;
border: 1px solid gray;
}
.page {
position: absolute;
display: block;
margin: 0 auto;
width: 70%;
height: 70%;
right: 3%;
top: 13%;
}
#yours {
width: 30%;
height: 22%;
position: absolute;
top: 1px;
right: -1px;
border: 0px;
}
#theirs {
width: 100%;
height: 100%;}
.loginList{
width: 25%;
height: 70%;
position: absolute;
top: 13%;
left: 0;
background: #9c9c9c;
}
.loginList>.title{
width: 100%;
height: 10%;
text-align: center;
line-height: 130%;
font-size: 30px;
font-family: "幼圆";
letter-spacing: 10px;
color: #607D8B;
background: #12c2ff;
}.loginList>.list{
width: 100%;
overflow-y: scroll;
height: 90%;
}
.loginList>.list>div {
width: 100%;
height: 6%;
border-bottom: 1px solid black;
border-top: solid 1px black;
text-align: center;
font-size: 23px;
font-family: "微软雅黑";
line-height:130% ;
letter-spacing: 7px;
}
.loginList>.list>div>button {
height: 100%;
width: 60px;
position: relative;
float: right;
}
.userName{
}
</style>
</head>
<body>
<div id="call-page" class="page">
<video id="yours" autoplay=""></video>
<video id="theirs" autoplay=""></video>
</div>
<div class="loginList">
<div class="title">在线人员</div>
<div class="list"></div>
</div>
<script >
var loginUser={};
try{
loginUser=JSON.parse(decodeURI(window.location.search.split("=")[1]));
}catch (e) {
location.href="index.html"
}
if(loginUser.userName){
location.href="index.html"
}
var connection= new WebSocket('wss://'+location.host);
//var connection = new WebSocket('http://localhost:8181');
var name = "";
var theirUsernameInput = document.querySelector('#their-username'),
callButton = document.querySelector('#call'),
hangUpButton = document.querySelector('#hang-up');
name=loginUser.name;
// Login when the user clicks the button
connection.onopen = function() {
send({
type: "login",
name: name
});
console.log("Connected");
};
// Handle all messages through this callback
connection.onmessage = function(message) {
//alert(JSON.stringify(message.data));
console.log("Got message", message.data);
var data = JSON.parse(message.data);
switch (data.type) {
case "login":
onLogin(data.success);
break;
case "offer":
var r=msgLog("是否接受\""+data.name+"\"的视频邀请");
if(r){
onOffer(data.offer, data.name);
}else{
send({type:"isCall",data:data.name,name:name})
}
break;
case "answer":
onAnswer(data.answer);
break;
case "candidate":
onCandidate(data.candidate);
break;
case "leave":
onLeave();
break;
case "loginState":
refreshList(data);
break;
case "isCall":
alert(data.name+"拒绝了您的邀请。")
break;
default:
break;
}
};
connection.onerror = function(err) {
console.log("Got error", err);
};
// Alias for sending messages in JSON format
function send(message) {
if (connectedUser) {
message.name = connectedUser;
}
connection.send(JSON.stringify(message));
};
function msgLog(str) {
return window.confirm(str);
}
function onLogin(success) {
if (success === false) {
alert("此用户名已有人使用请重新登录");
location.href="index.html";
} else {
// Get the plumbing ready for a call
startConnection();
}
};
function call(dom) {
if(dom.textContent==='连接'){
var theirUsername = dom.parentNode.querySelector('span').textContent;
if (theirUsername.length > 0) {
startPeerConnection(theirUsername);
}
}else {
breakCall();
}
}
function breakCall() {
send({
type: "leave"
});
onLeave();
}
function onOffer(offer, name) {
connectedUser = name;
yourConnection.setRemoteDescription(new RTCSessionDescription(offer));
yourConnection.createAnswer(function(answer) {
yourConnection.setLocalDescription(answer);
send({
type: "answer",
answer: answer
});
},
function(error) {
alert("An error has occurred");
});
}
function onAnswer(answer) {
yourConnection.setRemoteDescription(new RTCSessionDescription(answer));
}
function onCandidate(candidate) {
yourConnection.addIceCandidate(new RTCIceCandidate(candidate));
}
function onLeave() {
connectedUser = null;
theirVideo.src = null;
yourConnection.close();
yourConnection.onicecandidate = null;
yourConnection.onaddstream = null;
setupPeerConnection(stream);
}
function hasUserMedia() {
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
return !! navigator.getUserMedia;
}
function hasRTCPeerConnection() {
window.RTCPeerConnection = window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection;
window.RTCSessionDescription = window.RTCSessionDescription || window.webkitRTCSessionDescription || window.mozRTCSessionDescription;
window.RTCIceCandidate = window.RTCIceCandidate || window.webkitRTCIceCandidate || window.mozRTCIceCandidate;
return !! window.RTCPeerConnection;
}
var yourVideo = document.querySelector('#yours'),
theirVideo = document.querySelector('#theirs'),
yourConnection,
connectedUser,
stream;
function startConnection() {
if (hasUserMedia()) {
navigator.getUserMedia({
video: true,
audio: true
},
function(myStream) {
stream = myStream;
// yourVideo.src = window.URL.createObjectURL(stream);
window.stream = stream;
yourVideo.srcObject = stream;
yourVideo.muted=true;
if (hasRTCPeerConnection()) {
setupPeerConnection(stream);
} else {
alert("Sorry, your browser does not support WebRTC.");
}
},
function(error) {
console.log(error);
});
} else {
alert("Sorry, your browser does not support WebRTC.");
}
}
function setupPeerConnection(stream) {
var configuration = { iceServers : [{ "urls" :
navigator.mozGetUserMedia ? "stun:stun.services.mozilla.com" :
navigator.webkitGetUserMedia ? "stun:stun.l.google.com:19302" :
"stun:23.21.150.121"
},
{urls: "stun:stun.l.google.com:19302"},
{urls: "stun:stun1.l.google.com:19302"},
{urls: "stun:stun2.l.google.com:19302"},
{urls: "stun:stun3.l.google.com:19302"},
{urls: "stun:stun4.l.google.com:19302"},
{urls: "stun:23.21.150.121"},
{urls: "stun:stun01.sipphone.com"},
{urls: "stun:stun.ekiga.net"},
{urls: "stun:stun.fwdnet.net"},
{urls: "stun:stun.ideasip.com"},
{urls: "stun:stun.iptel.org"},
{urls: "stun:stun.rixtelecom.se"},
{urls: "stun:stun.schlund.de"},
{urls: "stun:stunserver.org"},
{urls: "stun:stun.softjoys.com"},
{urls: "stun:stun.voiparound.com"},
{urls: "stun:stun.voipbuster.com"},
{urls: "stun:stun.voipstunt.com"},
{urls: "stun:stun.voxgratia.org"},
{urls: "stun:stun.xten.com"}
] };
yourConnection = new RTCPeerConnection(configuration);
// Setup stream listening
yourConnection.addStream(stream);
yourConnection.onaddstream = function(e) {
//theirVideo.src = window.URL.createObjectURL(e.stream);
theirVideo.srcObject = e.stream;
};
// Setup ice handling
yourConnection.onicecandidate = function(event) {
if (event.candidate) {
send({
type: "candidate",
candidate: event.candidate
});
}
}
}
function startPeerConnection(user) {
connectedUser = user;
// Begin the offer
yourConnection.createOffer(function(offer) {
send({
type: "offer",
offer: offer
});
yourConnection.setLocalDescription(offer);
},
function(error) {
alert("An error has occurred.")
});
}
function refreshList(data){
var loginUsers= document.querySelector(".loginList>.list");
var list=data.list;
var htmlStr="";
console.log(data.list);
for(var i=0;i<list.length;i++){
var userListHt='<div><span>'+list[i]+ '</span><button onclick="call(this)">连接</button>' +"</div>";
htmlStr+=userListHt;
}
loginUsers.innerHTML=htmlStr;
}
window.onbeforeUnload=function () {
connection.close()
}
</script>
</body>
</html>
webSocket.js nodejs文件
//var WebSocketServer = require('wss');
var WebSocketServer = require('wss');
let fs = require("fs");
var https = require('https');
var privateKey=process.cwd()+'/server.key';//我把秘钥文件放在运行命令的目录下测试
var certificate=process.cwd()+'/server.crt';//console.log(keypath);
var credentials = {key: fs.readFileSync(privateKey),cert: fs.readFileSync(certificate) };
let server = https.createServer(credentials, (req, res) => {
if(req.url!='/'){
var textType= req.url.split('.').length>0?req.url.split('.')[1]:'html'
textType=textType.split('?')[0];
var fileUrl=process.cwd()+'/RTCDom'+req.url.split("?")[0];
res.writeHead(200,{'Content-Type':'text/'+textType})
fs.exists(fileUrl,function (e) {
console.log(fileUrl);
console.log(e)
console.log(textType)
if(e){
fs.readFile(fileUrl,function (err,data) {
if(err){
throw err;
}
res.end(data)
console.log(data)
})
}else{
fs.readFile('RTCDom/index.html',function(e,data){
if(e){
throw e;
}
res.end(data);
})
}
})
}
else{
fs.readFile('RTCDom/index.html',function(e,data){
if(e){
throw e;
}
res.end(data);
})
}
// res.end("this is a websocket server \n");
}).listen(8181,'192.168.101.5', function() {
// hostname是const类型时,可以用以下写法
//console.log('Server running at http://${hostname}:${port}/');
console.log('Server running at https://%s:%s', '192.168.101.5', 8181);
// console.log('Server running at http://' + hostname + ':' + port + '/');
});
var wss = new WebSocketServer({ server: server });
//var wss = new WebSocketServer({ port:8181});
users = {};
userList=[];
wss.on('connection',
function(connection) {
console.log("User connected");
connection.on('message',
function(message) {
var data;
try {
data = JSON.parse(message);
} catch(e) {
console.log("Error parsing JSON");
data = {};
}
switch (data.type) {
case "login":
console.log("User logged in as", data.name);
if (users[data.name]) {
sendTo(connection, {
type: "login",
success: false
});
} else {
users[data.name] = connection;
connection.name = data.name
userList.push(data.name);
userList.splice( userList.indexOf("undefined"), userList.indexOf("undefined")+1);
sendTo(connection, {
type: "login",
success: true
});
for(var _i in users){
console.log(_i)
if(users[_i]){
var _userList=[];
for(var _v=0;_v<userList.length;_v++){
if(userList[_v]!=_i){
_userList.push(userList[_v]);
}else{
continue;
}
}
sendTo(users[_i], {
type: "loginState",
list: _userList
});
}
}
}
break;
case "offer":
console.log("Sending offer to", data.name);
var conn = users[data.name];
if (conn != null) {
connection.otherName = data.name;
sendTo(conn, {
type: "offer",
offer: data.offer,
name: connection.name
});
}
break;
case "answer":
console.log("Sending answer to", data.name);
var conn = users[data.name];
if (conn != null) {
connection.otherName = data.name;
sendTo(conn, {
type: "answer",
answer: data.answer
});
}
break;
case "candidate":
console.log("Sending candidate to", data.name);
var conn = users[data.name];
if (conn != null) {
sendTo(conn, {
type: "candidate",
candidate: data.candidate
});
}
break;
case "leave":
console.log("Disconnecting user from", data.name);
var conn = users[data.name];
conn.otherName = null;
if (conn != null) {
sendTo(conn, {
type: "leave"
});
}
break;
case "isCall":
var conn = users[data.data];
sendTo(conn, {
type: "isCall",
name:data.name
});
default:
sendTo(connection, {
type: "error",
message: "Unrecognized command:" + data.type
});
break;
}
});
function sendTo(conn, message) {
conn.send(JSON.stringify(message));
}
connection.on('close',
function() {
if (connection.name) {
delete users[connection.name];
if (connection.otherName) {
console.log("Disconnecting user from", connection.otherName);
var conn = users[connection.otherName];
conn.otherName = null;
if (conn != null) {
sendTo(conn, {
type: "leave"
});
}
}
console.log(connection.name);
userList.splice(userList.indexOf(connection.name),userList.indexOf(connection.name)+1);
for(var _i in users){
console.log(_i)
if(users[_i]){
var _userList=[];
for(var _v=0;_v<userList.length;_v++){
if(userList[_v]!=_i){
_userList.push(userList[_v]);
}else{
continue;
}
}
console.log(_userList);
sendTo(users[_i], {
type: "loginState",
list: _userList
});
}
console.log(userList)
}
}
});
connection.send('{"hello":"hello123"}');
});
wss.on('listening',
function() {
console.log("Server started...");
});
效果图


2044




被折叠的 条评论
为什么被折叠?



