要在页面中正确显示上述代码,需要做以下几个调整:
将视频通话和聊天部分的代码放在不同的
<div>
容器中,确保它们不会混在一起。在页面的
<head>
标签中添加一个样式表(CSS)来设置布局和样式。调整脚本部分以确保逻辑正确,并确保 WebSocket 服务器地址和端口正确可访问。
下面是修改后的示例代码:
<!DOCTYPE html>
<html>
<head>
<title>Video Demo</title>
<link rel="shortcut icon" href="#" />
<style>
/* 添加样式以设置布局 */
#video-container {
display: flex;
justify-content: space-between;
margin-bottom: 20px;
}
#videos {
display: flex;
justify-content: center;
}
#chat-container {
border-top: 1px solid #ccc;
padding-top: 10px;
}
</style>
</head>
<body>
<h1>视频通话</h1>
<div id="video-container">
<div id="videos">
<video id="localVideo" autoplay muted playsinline></video>
<video id="remoteVideo" autoplay playsinline></video>
</div>
<div id="buttons">
<input id="roomId" type="text" placeholder="请输入房间ID" maxlength='40' />
<button id="joinBtn" type="button">加入</button>
<button id="leaveBtn" type="button">离开</button>
</div>
</div>
<h1>简易聊天</h1>
<div id="chat-container">
<div id="app">
<input id="sendMsg" type="text" />
<button id="submitBtn">发送</button>
</div>
</div>
<!-- 引入 JavaScript 文件 -->
<script src="js/main.js"></script>
<script src="js/adapter-later.js"></script>
<script type="text/javascript">
// 在页面显示聊天内容
function showMessage(str, type) {
var div = document.createElement("div");
div.innerHTML = str;
if (type == "enter") {
div.style.color = "blue";
} else if (type == "leave") {
div.style.color = "red";
}
document.getElementById("chat-container").appendChild(div);
}
// 新建一个 WebSocket
var websocket = new WebSocket("wss://192.168.1.134:8098/ws");
// 打开 WebSocket 连接
websocket.onopen = function () {
console.log("已经连上服务器");
document.getElementById("submitBtn").onclick = function () {
var txt = document.getElementById("sendMsg").value;
if (txt) {
// 向服务器发送数据
websocket.send(txt);
}
};
};
// 关闭连接
websocket.onclose = function () {
console.log("WebSocket closed");
};
// 接收服务器返回的数据
websocket.onmessage = function (e) {
var mes = JSON.parse(e.data); // json格式
showMessage(mes.data, mes.type);
};
</script>
</body>
</html>
请注意,此示例仅涉及布局和显示方面的调整,并未验证代码的完整功能。你可能需要确保提供正确的视频和聊天逻辑以使其正常工作。
内容由零声教学AI助手提供,问题来源于学员提问