index.html 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  7. <title>car</title>
  8. <script src="./socket.io.min.js"></script>
  9. <style>
  10. video {
  11. width: 500px;
  12. height: 400px;
  13. background: none;
  14. object-fit: fill;
  15. border: solid 1px red;
  16. }
  17. </style>
  18. </head>
  19. <body>
  20. <div>
  21. <video id="v2" autoplay playsinline muted></video>
  22. </div>
  23. <!-- webrtc -->
  24. <script>
  25. let RTC = null
  26. const socket = io({
  27. auth: {
  28. roomID: "feiCar",
  29. name: "ctrl",
  30. },
  31. transports: ["websocket"],
  32. });
  33. socket.on("connect", async () => {
  34. RTC = new RTCPeerConnection({ bundlePolicy: "max-bundle" });
  35. // listen state
  36. RTC.onicegatheringstatechange = () => {
  37. console.log("GatheringState: ", RTC.iceGatheringState);
  38. if (RTC.iceGatheringState === "complete") {
  39. const answer = RTC.localDescription;
  40. socket.emit("msg", answer);
  41. }
  42. };
  43. // listen track
  44. RTC.ontrack = (evt) => {
  45. console.log("track", evt.streams[0]);
  46. const video = document.getElementById("v2");
  47. video.srcObject = evt.streams[0];
  48. };
  49. console.log("连接成功监听webrtc");
  50. });
  51. // 发送anwser
  52. socket.on("msg", async (data) => {
  53. console.log("用户信息", data);
  54. if (data.type == "offer") {
  55. await this.Peer.setRemoteDescription(data);
  56. const answer = await this.Peer.createAnswer();
  57. await this.Peer.setLocalDescription(answer);
  58. }
  59. });
  60. // 监听加入
  61. socket.on('joined', user => {
  62. console.log(`${user.name}加入${user.roomID}房间`)
  63. // 向其它用户发送开始webrtc
  64. socket.emit('msg', { type: 'startRTC' })
  65. })
  66. // 监听离开
  67. socket.on('leaved', user => {
  68. console.log(`${user.name}离开${user.roomID}房间`)
  69. RTC.close()
  70. location.reload()
  71. })
  72. // 断开连接
  73. socket.on("connect_error", (err) => {
  74. console.log("连接错误", err);
  75. if (RTC) RTC.close()
  76. });
  77. </script>
  78. </body>
  79. </html>