| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110 |
- // wrt + socket + contrl
- const io = require("socket.io-client")
- const RTCVideoSource = require('./lib/videoSource')
- //const PWM = require('./lib/Pwm')
- const { RTCPeerConnection, MediaStream } = require("wrtc")
- const HOST = 'ws://10.10.3.196:7896'
- class CarServer {
- constructor(HOST) {
- this.webRTC = null
- this.mediaStream = null
- this.videoSource = null
- this.socket = io(HOST, {
- auth: {
- roomID: "feiCar",
- name: 'car'
- }
- });
- this.socket.on('connect', () => {
- this.connect()
- })
- this.socket.on('leaved', user => {
- console.log(`${user.name}离开${user.roomID}房间`)
- // 用户离开移除RTC
- this.destroyed()
- })
- this.socket.on('joined', user => {
- console.log(`${user.name}加入${user.roomID}房间`)
- // 发送offer
- this.createOffer()
- })
- this.socket.on('msg', data => {
- console.log('用户信息', data.type);
- this.msg(data)
- })
- this.socket.on('connect_error', err => {
- console.log('连接错误', err)
- this.destroyed()
- })
- }
- // 连接
- connect() {
- console.log('连接成功,开始初始化webrtc')
- // 初始化rtc
- this.webRTC = new RTCPeerConnection()
- // 初始化媒体源
- this.mediaStream = new MediaStream()
- this.videoSource = new RTCVideoSource()
- // 加入媒体源
- const videoTrack = this.videoSource.createTrack()
- this.mediaStream.addTrack(videoTrack)
- this.webRTC.addTrack(videoTrack, this.mediaStream)
- // 开始媒体
- this.videoSource.start()
- // 监听ice
- this.webRTC.onicecandidate = event => {
- if (event.candidate) {
- // 发送ICE
- this.socket.emit('msg', {
- type: 'candidate',
- candidate: event.candidate
- })
- }
- }
- // 监听ice状态
- this.webRTC.oniceconnectionstatechange = () => {
- if (this.webRTC.iceConnectionState === 'failed' || this.webRTC.iceConnectionState === 'closed' || this.webRTC.iceConnectionState === "disconnected") {
- console.log('ICE 连接失败')
- this.destroyed()
- }
- }
- }
- // 用户信息
- msg(data){
- if (data.type === 'answer') {
- // 设置本地应答
- this.webRTC.setRemoteDescription(data.answer)
- } else if (data.type === 'candidate') {
- // 本地设置ICE
- this.webRTC.addIceCandidate(data.candidate)
- } else if (data.type === 'conctrl') {
- // 控制信息
- //PWM.changPWM(data.conctrl)
- } else if (data.type === 'startRTC') {
- // 向其它房间人发送offer
- this.createOffer()
- }
- }
- // 创建offer
- async createOffer() {
- // 创建offer
- const offer = await this.webRTC.createOffer()
- this.webRTC.setLocalDescription(offer)
- // 发送offer
- this.socket.emit('msg', {
- type: 'offer',
- offer: offer
- })
- }
- destroyed() {
- if (this.webRTC) this.webRTC.close()
- if (this.videoSource) this.videoSource.stop()
- this.webRTC = null
- this.mediaStream = null
- this.videoSource = null
- process.exit(1)
- }
- }
- new CarServer(HOST)
|