Webrtc WebSocket实现音视频通讯

转载地址:http://blog.csdn.net/chenhande1990chenhan/article/details/72831782


一般的浏览器都集成了webrtc的功能,因此是不需要webrtc服务器就可以在局域网内进行点对点的音视频通讯。

本文主要利用websocket进行通讯,支持个google浏览器,无法兼容Firefox浏览器,同时对于Tomcat要求8.0以上,同时由于最新的webrtc要么用localhost访问,如果要用IP访问,则只能用https协议进行访问,因此这些都是需要解决的问题,本文只是一个demon程序。



[html]  view plain  copy
  1. <%@ page language="java" pageEncoding="UTF-8" %>  
  2. <!DOCTYPE html>  
  3. <html>  
  4. <head>  
  5.     <title>Java后端WebSocket的Tomcat实现</title>  
  6. </head>  
  7. <body>  
  8.     Welcome<br/><input id="text" type="text"/>  
  9.     <button onclick="send()">发送消息</button>  
  10.     <hr/>  
  11.     <button onclick="closeWebSocket()">关闭WebSocket连接</button>  
  12.     <hr/>  
  13.     <div id="message"></div>  
  14.       
  15.     <video id="vid1" width="640" height="480" autoplay></video>  
  16.     <video id="vid2" width="640" height="480" autoplay></video><br>  
  17.     <a id="create" href="/Websocket/#true" onclick="init()">点击此链接新建聊天室</a><br>  
  18.     <p id="tips" style="background-color:red">请在其他浏览器中打开:http://此电脑   加入此视频聊天</p>  
  19. </body>  
  20.   
  21. <script type="text/javascript">  
  22.     var isCaller = window.location.href.split('#')[1];  
  23.     var websocket = null;  
  24.     //判断当前浏览器是否支持WebSocket  
  25.     if ('WebSocket' in window) {  
  26.         websocket = new WebSocket("ws://localhost:8080/Websocket/websocket");  
  27.     }  
  28.     else {  
  29.         alert('当前浏览器 Not support websocket')  
  30.     }  
  31.   
  32.     //连接发生错误的回调方法  
  33.     websocket.onerror = function () {  
  34.         setMessageInnerHTML("WebSocket连接发生错误");  
  35.     };  
  36.   
  37.     //连接成功建立的回调方法  
  38.     websocket.onopen = function () {  
  39.         setMessageInnerHTML("WebSocket连接成功");  
  40.     }  
  41.   
  42.  // 创建PeerConnection实例 (参数为null则没有iceserver,即使没有stunserver和turnserver,仍可在局域网下通讯)  
  43.     var pc = new webkitRTCPeerConnection(null);  
  44.   
  45.     // 发送ICE候选到其他客户端  
  46.     pc.onicecandidate = function(event) {  
  47.         setMessageInnerHTML("我看看 1");  
  48.         if (event.candidate !== null) {  
  49.             setMessageInnerHTML("我看看 2");  
  50.             websocket.send(JSON.stringify({  
  51.                 "event" : "_ice_candidate",  
  52.                 "data" : {  
  53.                     "candidate" : event.candidate  
  54.                 }  
  55.             }));  
  56.         }  
  57.     };  
  58.       
  59.     //接收到消息的回调方法  
  60.     websocket.onmessage = function (event) {  
  61.         setMessageInnerHTML("接收到的信息");  
  62.         setMessageInnerHTML(event.data);  
  63.         if(event.data=="new user") {  
  64.             console.log("new user");  
  65.             location.reload();  
  66.         } else {  
  67.             var json = JSON.parse(event.data);  
  68.             console.log('onmessage: ', json);  
  69.             //如果是一个ICE的候选,则将其加入到PeerConnection中,否则设定对方的session描述为传递过来的描述  
  70.             if (json.event === "_ice_candidate") {  
  71.                 pc.addIceCandidate(new RTCIceCandidate(json.data.candidate));  
  72.             } else {  
  73.                 pc.setRemoteDescription(new RTCSessionDescription(json.data.sdp));  
  74.                 // 如果是一个offer,那么需要回复一个answer  
  75.                 if (json.event === "_offer") {  
  76.                     pc.createAnswer(sendAnswerFn, function(error) {  
  77.                         console.log('Failure callback: ' + error);  
  78.                     });  
  79.                 }  
  80.             }  
  81.         }  
  82.     }  
  83.   
  84.     //连接关闭的回调方法  
  85.     websocket.onclose = function () {  
  86.         setMessageInnerHTML("WebSocket连接关闭");  
  87.     }  
  88.   
  89.     //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。  
  90.     window.onbeforeunload = function () {  
  91.         closeWebSocket();  
  92.     }  
  93.   
  94.     //将消息显示在网页上  
  95.     function setMessageInnerHTML(innerHTML) {  
  96.         document.getElementById('message').innerHTML += innerHTML + '<br/>';  
  97.     }  
  98.   
  99.     //关闭WebSocket连接  
  100.     function closeWebSocket() {  
  101.         websocket.close();  
  102.     }  
  103.   
  104.     //发送消息  
  105.     function send() {  
  106.         var message = document.getElementById('text').value;  
  107.         websocket.send(message);  
  108.     }  
  109.       
  110.  // stun和turn服务器  
  111.     var iceServer = {  
  112.         "iceServers" : [ {  
  113.             "url" : "stun:stun.l.google.com:19302"  
  114.         }, {  
  115.             "url" : "turn:numb.viagenie.ca",  
  116.             "username" : "webrtc@live.com",  
  117.             "credential" : "muazkh"  
  118.         } ]  
  119.     };  
  120.   
  121.       
  122.   
  123.     // 如果检测到媒体流连接到本地,将其绑定到一个video标签上输出  
  124.     pc.onaddstream = function(event) {  
  125.         document.getElementById('vid2').src = URL  
  126.                 .createObjectURL(event.stream);  
  127.     };  
  128.   
  129.     // 发送offer和answer的函数,发送本地session描述  
  130.     var sendOfferFn = function(desc) {  
  131.         pc.setLocalDescription(desc);  
  132.         websocket.send(JSON.stringify({  
  133.             "event" : "_offer",  
  134.             "data" : {  
  135.                 "sdp" : desc  
  136.             }  
  137.         }));  
  138.     }, sendAnswerFn = function(desc) {  
  139.         pc.setLocalDescription(desc);  
  140.         websocket.send(JSON.stringify({  
  141.             "event" : "_answer",  
  142.             "data" : {  
  143.                 "sdp" : desc  
  144.             }  
  145.         }));  
  146.     };  
  147.   
  148.     // 获取本地音频和视频流  
  149.     navigator.webkitGetUserMedia({  
  150.         "audio" : true,  
  151.         "video" : true  
  152.     },  
  153.             function(stream) {  
  154.                 //绑定本地媒体流到video标签用于输出  
  155.                 document.getElementById('vid1').src = URL  
  156.                         .createObjectURL(stream);  
  157.                 //向PeerConnection中加入需要发送的流  
  158.                 pc.addStream(stream);  
  159.                 //如果是发起方则发送一个offer信令  
  160.                 if (isCaller) {  
  161.                     pc.createOffer(sendOfferFn, function(error) {  
  162.                         console.log('Failure callback: ' + error);  
  163.                     });  
  164.                 }   
  165.             }, function(error) {  
  166.                 //处理媒体流创建失败错误  
  167.                 console.log('getUserMedia error: ' + error);  
  168.             });  
  169.       
  170.     window.onload=function(){   
  171.         if(isCaller==null||isCaller==undefined) {  
  172.             var tips = document.getElementById("tips");  
  173.             tips.remove();  
  174.         } else {  
  175.             var create = document.getElementById("create");  
  176.             create.remove();  
  177.         }  
  178.     };  
  179.     function init() {  
  180.         location.reload();  
  181.     }  
  182. </script>  
  183. </html>  

[java]  view plain  copy
  1. package me.gacl.websocket;  
  2.   
  3. import java.io.IOException;  
  4. import java.util.concurrent.CopyOnWriteArraySet;  
  5.   
  6. import javax.websocket.*;  
  7. import javax.websocket.server.ServerEndpoint;  
  8.   
  9. /** 
  10.  * @ServerEndpoint 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端, 
  11.  * 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端 
  12.  */  
  13. @ServerEndpoint("/websocket")  
  14. public class WebSocketTest {  
  15.     //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。  
  16.     private static int onlineCount = 0;  
  17.   
  18.     //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识  
  19.     private static CopyOnWriteArraySet<WebSocketTest> webSocketSet = new CopyOnWriteArraySet<WebSocketTest>();  
  20.   
  21.     //与某个客户端的连接会话,需要通过它来给客户端发送数据  
  22.     private Session session;  
  23.   
  24.     /** 
  25.      * 连接建立成功调用的方法 
  26.      * @param session  可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据 
  27.      */  
  28.     @OnOpen  
  29.     public void onOpen(Session session){  
  30.         this.session = session;  
  31.         webSocketSet.add(this);     //加入set中  
  32.         addOnlineCount();           //在线数加1  
  33.         System.out.println(session.getId()+"有新连接加入!当前在线人数为" + getOnlineCount());  
  34.     }  
  35.   
  36.     /** 
  37.      * 连接关闭调用的方法 
  38.      */  
  39.     @OnClose  
  40.     public void onClose(){  
  41.         webSocketSet.remove(this);  //从set中删除  
  42.         subOnlineCount();           //在线数减1  
  43.         System.out.println(session.getId()+"有一连接关闭!当前在线人数为" + getOnlineCount());  
  44.     }  
  45.   
  46.     /** 
  47.      * 收到客户端消息后调用的方法 
  48.      * @param message 客户端发送过来的消息 
  49.      * @param session 可选的参数 
  50.      */  
  51.     @OnMessage  
  52.     public void onMessage(String message, Session session) {  
  53.         System.out.println(session.getId()+"来自客户端的消息:" + message);  
  54.         //群发消息  
  55.         for(WebSocketTest item: webSocketSet){  
  56.             try {  
  57.                 item.sendMessage(message);  
  58.             } catch (IOException e) {  
  59.                 e.printStackTrace();  
  60.                 continue;  
  61.             }  
  62.         }  
  63.     }  
  64.   
  65.     /** 
  66.      * 发生错误时调用 
  67.      * @param session 
  68.      * @param error 
  69.      */  
  70.     @OnError  
  71.     public void onError(Session session, Throwable error){  
  72.         System.out.println("发生错误");  
  73.         error.printStackTrace();  
  74.     }  
  75.   
  76.     /** 
  77.      * 这个方法与上面几个方法不一样。没有用注解,是根据自己需要添加的方法。 
  78.      * @param message 
  79.      * @throws IOException 
  80.      */  
  81.     public void sendMessage(String message) throws IOException{  
  82.         this.session.getBasicRemote().sendText(message);  
  83.         //this.session.getAsyncRemote().sendText(message);  
  84.     }  
  85.   
  86.     public static synchronized int getOnlineCount() {  
  87.         return onlineCount;  
  88.     }  
  89.   
  90.     public static synchronized void addOnlineCount() {  
  91.         WebSocketTest.onlineCount++;  
  92.     }  
  93.   
  94.     public static synchronized void subOnlineCount() {  
  95.         WebSocketTest.onlineCount--;  
  96.     }  
  97. }  

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值