直播間一對一展示代碼
webrtc+websocket 直接上代碼
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
@Component
@ServerEndpoint("/groupChat/{roomId}/{username}")
public class GroupChatController {
// 保存 聊天室id -> 聊天室成員 的映射關系
private static ConcurrentHashMap<String, List<Session>> rooms = new ConcurrentHashMap<>();
// 收到訊息呼叫的方法,群成員發送訊息
@OnMessage
public void onMessage(@PathParam("roomId") String roomId,
@PathParam("username") String username, String message) {
List<Session> sessionList = rooms.get(roomId);
System.out.println("sessionList"+sessionList);
// 分別向聊天室的成員發送訊息
for (Session session : sessionList) {
try {
String text=username+": "+message;
session.getBasicRemote().sendText(text);
} catch (IOException e) {
e.printStackTrace();
}
}
// lambda運算式寫法
// sessionList.forEach(item -> {
// try {
// String text = username + ": " + message;
// item.getBasicRemote().sendText(text);
// } catch (IOException e) {
// e.printStackTrace();
// }
// });
}
// 建立連接呼叫的方法,群成員加入
@OnOpen
public void onOpen(Session session, @PathParam("roomId") String roomId, @PathParam("name") String name) {
List<Session> sessionList = rooms.get(roomId);
if (sessionList == null) {
sessionList = new ArrayList<>();
rooms.put(roomId, sessionList);
}
sessionList.add(session);
System.out.println("成員加入---- 聊天室號:" + roomId + " 當前聊天室人數:" + sessionList.size());
}
// 關閉連接呼叫的方法,群成員退出
@OnClose
public void onClose(Session session, @PathParam("roomId") String roomId) {
List<Session> sessionList = rooms.get(roomId);
sessionList.remove(session);
System.out.println("成員退出---- 聊天室號:" + roomId + " 當前聊天室人數:" + sessionList.size());
}
// 傳輸訊息錯誤呼叫的方法
@OnError
public void one rror(Throwable error) {
System.out.println("訊息傳遞出錯");
}
}
<style>
.container {
margin-top: 30px;
margin-left: 30px;
}
.span1 {
display: inline-block;
width: 80px;
font-size: 13px;
}
input {
width: 200px;
height: 30px;
outline: none;
border: 1px solid #3998f7;
border-radius: 3px;
padding: 0 10px;
}
input:hover,
textarea:hover {
box-shadow: 0 0 3px #3998f7;
}
#name {
margin-top: 15px;
}
button {
width: 100px;
height: 30px;
outline: none;
color: #fff;
font-size: 13px;
font-weight: bold;
background-color: #168ed1;
border: none;
border-radius: 5px;
cursor: pointer;
}
#connectBtn,
#content,
#sendBtn,
#closeBtn {
margin-top: 10px;
}
#messages {
margin-top: 20px;
}
textarea {
width: 300px;
height: 80px;
outline: none;
border: 1px solid #3998f7;
border-radius: 3px;
color: rgba(0, 0, 0, 0.7);
font-size: 13px;
font-weight: bold;
padding: 5px;
}
#messages, .me, .name {
color: rgba(0, 0, 0, 0.7);
font-size: 14px;
font-weight: bold;
}
.me {
color: red;
}
.name {
color: royalblue;
}
</style>
昵稱:
重繪
連接
發送 退出
網上看著扒下來的一個 聊天室 前端后端
視頻直播加聊天室
昵稱:
重繪
連接
發送 退出
js代碼
// 產生亂數
if (!location.hash) {
location.hash = Math.floor(Math.random() * 0xFFFFFF).toString(16);
}
// 獲取房間號
var roomHash = location.hash.substring(1);
// 放置你自己的頻道id, 這是我注冊了 ScaleDrone 官網后,創建的channel
// 你也可以自己創建
var drone = new ScaleDrone(‘87fYv4ncOoa0Cjne’);
// 房間名必須以 'observable-'開頭
var roomName = ‘observable-’ + roomHash;
var configuration = {
iceServers: [{
urls: ‘stun:stun.l.google.com:19302’ // 使用谷歌的stun服務
}]
};
var room;
var pc;
function onSuccess() {}
function one rror(error) {
console.error(error);
}
drone.on(‘open’, function(error){
if (error) { return console.error(error);}
room = drone.subscribe(roomName);
room.on('open', function(error){
if (error) {onError(error);}
});
// 已經鏈接到房間后,就會收到一個 members 陣列,代表房間里的成員
// 這時候信令服務已經就緒
room.on('members', function(members){
console.log('MEMBERS', members);
// 如果你是第二個鏈接到房間的人,就會創建offer
var isOfferer = members.length === 2;
startWebRTC(isOfferer);
});
});
// 通過Scaledrone發送信令訊息
function sendMessage(message) {
drone.publish({
room: roomName,
message
});
}
function startWebRTC(isOfferer) {
pc = new RTCPeerConnection(configuration);
// 當本地ICE Agent需要通過信號服務器發送資訊到其他端時
// 會觸發icecandidate事件回呼
pc.onicecandidate = function(event){
if (event.candidate) {
sendMessage({ 'candidate': event.candidate });
}
};
// 如果用戶是第二個進入的人,就在negotiationneeded 事件后創建sdp
if (isOfferer) {
// onnegotiationneeded 在要求sesssion協商時發生
pc.onnegotiationneeded = function() {
// 創建本地sdp描述 SDP (Session Description Protocol) session描述協議
pc.createOffer().then(localDescCreated).catch(onError);
};
}
// 當遠程資料流到達時,將資料流裝載到video中
pc.onaddstream = function(event){
remoteVideo.srcObject = event.stream;
};
// 獲取本地媒體流
navigator.mediaDevices.getUserMedia({
audio: true,
video: true,
}).then( function(stream) {
// 將本地捕獲的視頻流裝載到本地video中
localVideo.srcObject = stream;
// 將本地流加入RTCPeerConnection 實體中 發送到其他端
pc.addStream(stream);
}, one rror);
// 從Scaledrone監聽信令資料
room.on('data', function(message, client){
// 訊息是我自己發送的,則不處理
if (client.id === drone.clientId) {
return;
}
if (message.sdp) {
// 設定遠程sdp, 在offer 或者 answer后
pc.setRemoteDescription(new RTCSessionDescription(message.sdp), function(){
// 當收到offer 后就接聽
if (pc.remoteDescription.type === 'offer') {
pc.createAnswer().then(localDescCreated).catch(onError);
}
}, one rror);
}
else if (message.candidate) {
// 增加新的 ICE canidatet 到本地的鏈接中
pc.addIceCandidate(
new RTCIceCandidate(message.candidate), onSuccess, one rror
);
}
});
}
function localDescCreated(desc) {
pc.setLocalDescription(desc, function(){
sendMessage({ ‘sdp’: pc.localDescription });
},onError);
}
這些都是網上扒下來整理啦一下 侵權什么的聯系我秒刪
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/139768.html
標籤:其他
