WebRTC 是一个支持网页浏览器进行实时语音对话或视频对话的技术 ,,最近工作需要研究了一下,写一个demo供大家参考,原理方面的东西大家可以百度一下,需要注意的是demo目前只支持火狐 因为谷歌目前必须是https 访问 才可以获取视频信息.系统环境为:tomcat8+jdk7

websocket

package com.li.web;

import java.io.IOException;

import java.util.HashMap;

import java.util.HashSet;

import java.util.Set;

import javax.websocket.OnClose;

import javax.websocket.OnMessage;

import javax.websocket.OnOpen;

import javax.websocket.Session;

import javax.websocket.server.PathParam;

import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/video/{roomId}/{userId}")

public class VideoScoket {

/**

* 存放房间与用户

*/

private static HashMap> usersRoom = new HashMap>();

/**

* 打开websocket

* @param session websocket的session

* @param uid 打开用户的UID

*/

@OnOpen

public void onOpen(Session session, @PathParam("roomId")String roomId, @PathParam("userId")String userId) {

Set users = usersRoom.get(roomId);

if(users== null ){

users = new HashSet();

}

if(users.size()>=2){

sendMessage(session, "peopleMax");//目前只支持两个人之间的通讯 ,所以不能超过两个人

}else{

User user = new User();

user.setId(userId);

user.setSession(session);

users.add(user);

usersRoom.put(roomId,users);

}

}

/**

* websocket关闭

* @param session 关闭的session

* @param uid 关闭的用户标识

*/

@OnClose

public void onClose(Session session, @PathParam("roomId")String roomId, @PathParam("userId")String userId) {

Set users = usersRoom.get(roomId);

if(users!=null){

for (User user:users) {

if(user.getId().equals(userId)){

users.remove(user);

return;

}else if(!user.getId().equals(userId)){

sendMessage(user.getSession(), "bye");//退出之后,发送给另一个人信息,以便让他断开视频连接

return;

}

}

}

}

/**

* 收到消息

* @param message 消息内容

* @param session 发送消息的session

* @param uid

*/

@OnMessage

public void onMessage(String message,Session session, @PathParam("roomId")String roomId, @PathParam("userId")String userId) {

Set users = usersRoom.get(roomId);

if(users!=null){

User recipient = null;

for (User user:users) {//查询当前会议中另一个在线人

if(!user.getId().equals(userId)){

recipient = user;

}

}

if(message.startsWith("query-On-line")){//如果查询是否有人在线

if(users.size()>1){

sendMessage(session,"query-On-line-Yes");

}else{

sendMessage(session,"query-On-line-No");

}

}else if(recipient!=null){

sendMessage(recipient.getSession(), message);

}

}

}

/**

* 给客户端发送消息

* @param session

* @param message

*/

public void sendMessage(Session session,String message){

try {

if(session.isOpen()) {

session.getBasicRemote().sendText(new String(message));

}

} catch (IOException e) {

e.printStackTrace();

}

}

}

User

package com.li.web;

import javax.websocket.Session;

public class User {

private String id;

private Session session;

public String getId() {

return id;

}

public void setId(String id) {

this.id = id;

}

public Session getSession() {

return session;

}

public void setSession(Session session) {

this.session = session;

}

}

meeting.jsp

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

String scoketPasePath = "ws://"+request.getServerName()+":"+request.getServerPort()+path+"/video/";

%>

.right{

height: 80%;

position:absolute;

right: 40px;

top:40px;

width:180px;

}

.remoteAudio{

margin-top: 20px;

list-style:outside none none;

height:150px;

width: 180px;

background-color: black;

border: 1px red solid;

text-align:center;

}

.name{

position:absolute;

z-index:99999;

left:77px;

}

function goRoom(){

var $roomId = $("#roomId").val();

if($roomId==""){

alert("请输入房间号");

}else{

monitor.initialize("", "localVideo","remoteAudio", $roomId);

monitor.openChannel();

}

}

monitor.js

var monitor ={

initSucess:false,

socket :null,

PeerConnection:null,

pc:null,

started:false,

localStream:null,

remoteVideo:null,

localVideo:null,

remoteStream:null,

scoketPath:null,

roomId:null,

userId:null,

socketSate:false,

iceServer:{//打洞服务器地址配置

"iceServers": [{

"url": "stun:1.1.1.1"

}]},

log:function(msg){

if(console && console.log){

console.log(msg);

}

},//初始化一些信息

initialize:function(scoketPath,localVideoId,remoteVideoId,roomId){

PeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;

monitor.remoteVideo = $("#"+remoteVideoId);

monitor.localVideo = $("#"+localVideoId);

monitor.scoketPath = scoketPath;

monitor.roomId = roomId;

monitor.userId = new Date().getTime();

},//打开webscoket

openChannel:function(){

monitor.socketSate=true;

monitor.socket = new WebSocket(monitor.scoketPath+monitor.roomId+"/"+monitor.userId);

monitor.socket.onopen = monitor.onopen;

monitor.socket.onmessage = monitor.onChannelMessage;

monitor.socket.onclose = monitor.onChannelClosed;

},

onopen:function(onopenCallBack){

monitor.log("websocket打开");

monitor.socketSate = true;

monitor.getUserMedia();

},

onChannelClosed:function(){

monitor.log("websocket关闭");

monitor.socketSate=false;

monitor.openChannel();

},

onChannelMessage:function(message){

monitor.log("收到信息 : " + message.data);

if(message.data=="query-On-line-Yes"){

monitor.maybeStart();

}else if(message.data=="peopleMax"){

alert("人数已经超过限制");

}else if(message.data=="bye"){

monitor.onRemoteClose();

}else if(message.data!="query-On-line-No"){

monitor.processSignalingMessage(message.data);//建立视频连接

}

},

getUserMedia:function(){

monitor.log("获取用户媒体");

navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;

navigator.getUserMedia({

"audio" : true,

"video" : true

},monitor.onUserMediaSuccess, monitor.onUserMediaError);

},

onUserMediaSuccess:function(stream){

monitor.log("获取媒体成功");

monitor.localStream=stream;

var url = window.URL.createObjectURL(stream);

monitor.localVideo.attr("src",url);

monitor.sendMessageByString("query-On-line");

},

onUserMediaError:function(){

monitor.log("获取用户流失败!");

},

maybeStart:function(){

if (!monitor.started) {

monitor.createPeerConnection();

monitor.pc.addStream(monitor.localStream);

monitor.started = true;

monitor.doCall();

}

},

createPeerConnection:function(){

monitor.pc = new PeerConnection(monitor.iceServer);

monitor.pc.onicecandidate =monitor.onIceCandidate;

monitor.pc.onconnecting = monitor.onSessionConnecting;

monitor.pc.onopen = monitor.onSessionOpened;

monitor.pc.onaddstream = monitor.onRemoteStreamAdded;

monitor.pc.onremovestream = monitor.onRemoteStreamRemoved;

},

onSessionConnecting:function(message){

monitor.log("开始连接");

},

onSessionOpened:function(message){

monitor.log("连接打开");

},

onRemoteStreamAdded:function(event){

monitor.log("远程视频添加");

if(monitor.remoteVideo!=null){

var url = window.URL.createObjectURL(event.stream);

monitor.remoteVideo.attr("src",url);

monitor.remoteStream = event.stream;

monitor.waitForRemoteVideo();

}

},

waitForRemoteVideo:function(){

if (monitor.remoteVideo[0].currentTime > 0) { // 判断远程视频长度

monitor.transitionToActive();

} else {

setTimeout(monitor.waitForRemoteVideo, 100);

}

},

transitionToActive:function(){

monitor.log("连接成功!");

monitor.sendMessageByString("connection_open");

},

onRemoteStreamRemoved:function(event){

monitor.log("远程视频移除");

},

onIceCandidate:function(event){

if (event.candidate) {

monitor.sendMessage({

type : "candidate",

label : event.candidate.sdpMLineIndex,

id : event.candidate.sdpMid,

candidate : event.candidate.candidate

});

} else {

monitor.log("End of candidates.");

}

},

processSignalingMessage:function(message){

var msg = JSON.parse(message);

if (msg.type === "offer") {

if (!monitor.started)

monitor.maybeStart();

monitor.pc.setRemoteDescription(new RTCSessionDescription(msg),function(){

monitor.doAnswer();

},function(){

});

} else if (msg.type === "answer" && monitor.started) {

monitor.pc.setRemoteDescription(new RTCSessionDescription(msg));

} else if (msg.type === "candidate" && monitor.started) {

var candidate = new RTCIceCandidate({

sdpMLineIndex : msg.label,

candidate : msg.candidate

});

monitor.pc.addIceCandidate(candidate);

}

},

doAnswer:function (){

monitor.pc.createAnswer(monitor.setLocalAndSendMessage, function(e){

monitor.log("创建相应失败"+e);

});

},

doCall:function(){

monitor.log("开始呼叫");

monitor.pc.createOffer(monitor.setLocalAndSendMessage,function(){

});

},

setLocalAndSendMessage:function(sessionDescription){

monitor.pc.setLocalDescription(sessionDescription);

monitor.sendMessage(sessionDescription);

},

sendMessage:function(message){

var msgJson = JSON.stringify(message);

monitor.sendMessageByString(msgJson);

},

sendMessageByString:function(message){

monitor.socket.send(message);

monitor.log("发送信息 : " + message);

},

onRemoteClose:function(){

monitor.started = false;

monitor.pc.close();

monitor.sendMessageByString("connection_colse");

}

};

还需要注意的一点是,,如果视频的两个人未处在同一个内网中,那则需要部署打洞服务器,,我用的restund 比较简单...有需要的同学可以百度,部署安装

webrtc java api_WEBRTC--简单入门实例相关推荐

  1. java oxm_Spring oxm入门实例

    o/xmapper是什么? spring3.0的一个新特性是o/xmapper.o/x映射器这个概念并不新鲜,o代表object,x代表xml.它的目的是在java对象(几乎总是一个plainoldj ...

  2. SpringMVC 基础教程 简单入门实例

    spring MVC 入门教程二: 一个简单的入门实例教程 该实例的源码和实例中的jar 源码:http://download.csdn.net/detail/swingpyzf/5348563 所需 ...

  3. vue服务端渲染 MySQL_vue服务端渲染简单入门实例

    想到要学习vue-ssr的同学,自不必多说,一定是熟悉了vue,并且多多少少做过几个项目.然后学习vue服务端渲染无非解决首屏渲染的白屏问题以及SEO友好. 话不多说,笔者也是研究多日才搞明白这个服务 ...

  4. Java正则表达式简单入门

    正则表达式,又称规则表达式.(英语:Regular Expression,在代码中常简写为regex.regexp或RE),计算机科学的一个概念.正则表达式是对字符串(包括普通字符(例如,a 到 z ...

  5. java dropwizard_Dropwizard简单入门

    其它开发库 除了Jetty.Jersey 和 Jackson,Dropwizard还包含了很多其它非常有帮助的开发库: Guava:支持不可变数据结构,提供日益丰富的Java工具类加速开发. Logb ...

  6. Java监听器完整入门实例

    什么是监听器 监听器就是一个实现了特定接口的Java类,这个Java类用于监听另一个Java类的方法调用或者属性的改变.当被监听对象发生上述事件后,监听器某个方法将会立即被执行. 监听器的用途 用来监 ...

  7. HttpClient4.5 简单入门实例(一)

    一.所需要的jar包 httpclient-4.5.jar httpcore-4.4.1.jar httpmime-4.5.jar 二.实例 package com.gblfy.test;import ...

  8. Spring简单入门实例

    前言 这一篇只是简单感受一下Spring MVC. 环境和jar包准备 1.  IDE- eclipse3.7 2. Spring 下载地址: ▪Spring3.2.3  -- http://repo ...

  9. Struts2简单入门实例

    2019独角兽企业重金招聘Python工程师标准>>> 1.安装JDK7 以及Tomcat7.0,详细步骤见之前的一篇日志中的前两个步骤,以下是链接: http://my.oschi ...

最新文章

  1. Nagios设置报警间隔
  2. SAP BW数据源增强管理
  3. WebService.asmx架设后,显示调用按钮的方法
  4. Python rang()函数
  5. 云在物联网中的惊人优势 | 技术头条
  6. 索引-css-第二版-pyhui
  7. 使用HttpClient 调用Web Api
  8. 数据科学和人工智能技术笔记 三、数据预处理
  9. OpenGL ES总结(三)OpenGL通过计算纹理坐标来显示一张图片
  10. 自己编译nvm-window,解决无法修改镜像下载node很慢的问题!
  11. 如何构建“正确的”云平台存储
  12. 获取OlapConnection连接
  13. java课程设计简易记事本
  14. QQ音乐爬虫(with scrapy)/QQ Music Spider
  15. ESB 企业服务总线
  16. 华为qq邮箱服务器密码忘了,华为手机qq邮箱无法登录电子邮件鉴权失败的解决办法...
  17. 不知道文字识别工具有哪些?来看看这几个好用的软件
  18. 【Redis】概述以及启动Redis并进入Redis
  19. 天融信防火墙重置配置_天融信防火墙认证配置
  20. 机架服务器和群晖存文件对比,如何选购群晖nas网络存储服务器?

热门文章

  1. 报任安书文言现象_干货丨文言文句式详解,快点收藏!
  2. 分布式锁简单入门以及三种实现方式介绍(滴滴)
  3. Hash索引和BTree索引
  4. 为什么说5G会提前于2018年到来?
  5. Linux时间 时区 同步
  6. lintcode :链表插入排序
  7. 方立勋_30天掌握JavaWeb_自定义标签
  8. Web三个域对象的区别
  9. [2018HN省队集训D8T1] 杀毒软件
  10. Windows 10 配置系统环境变量