index.html 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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({
  35. bundlePolicy: "max-bundle"
  36. });
  37. // listen state
  38. RTC.onicegatheringstatechange = () => {
  39. console.log("GatheringState: ", RTC.iceGatheringState);
  40. if (RTC.iceGatheringState === "complete") {
  41. const answer = RTC.localDescription;
  42. socket.emit("msg", answer);
  43. }
  44. };
  45. // listen track
  46. RTC.ontrack = (evt) => {
  47. console.log("track", evt.streams[0]);
  48. const video = document.getElementById("v2");
  49. video.srcObject = evt.streams[0];
  50. };
  51. console.log("连接成功监听webrtc");
  52. });
  53. // 发送anwser
  54. socket.on("msg", async (data) => {
  55. console.log("用户信息", data);
  56. if (data.type == "offer") {
  57. await this.Peer.setRemoteDescription(data);
  58. const answer = await this.Peer.createAnswer();
  59. await this.Peer.setLocalDescription(answer);
  60. }
  61. });
  62. // 监听加入
  63. socket.on('joined', user => {
  64. console.log(`${user.name}加入${user.roomID}房间`)
  65. // 向其它用户发送开始webrtc
  66. socket.emit('msg', { type: 'startRTC' })
  67. })
  68. // 监听离开
  69. socket.on('leaved', user => {
  70. console.log(`${user.name}离开${user.roomID}房间`)
  71. RTC.close()
  72. location.reload()
  73. })
  74. // 断开连接
  75. socket.on("connect_error", (err) => {
  76. console.log("连接错误", err);
  77. if (RTC) RTC.close()
  78. });
  79. </script>
  80. </body>
  81. </html>