【Javascript】【WebRTC】WebRTC从原理到实现(七):服务端代码

let sockets = new Array();
let rooms = new Array();

let WebSocketServer = require('ws').Server;
let server = new WebSocketServer({
    port: 1991
});

//服务启动
server.on('listening', function () {
    console.log("==========> service start");
});

//客户端连接成功
server.on('connection', function (socket) {
    //注册消息监听器
    socket.on('message', message => handleMessage(socket, message));
    //连接断开
    socket.on('close', function (code) {
        if (socket.state == 0)
            console.info("==========> client a disconnect");
        else
            console.info("==========> client b disconnect");
        for (let i = 0; i < sockets.length; i++)
            if (socket.roomid == sockets[i].roomid)
                sockets[i].close();
        for (let i = 0; i < rooms.length; i++)
            if (socket.roomid == rooms[i].roomid)
                rooms.slice(i--, 1);
        sockets = [];
    });
    //连接异常
    socket.on('error', function (error) {
        console.info("==========> connection exception")
    });
});

//处理消息
function handleMessage(socket, message) {
    message = JSON.parse(message);
    switch (message.type) {
        //客户端连接
        case "connect":
            //如果接听方先加入,退出
            if (message.state == 1 && rooms.indexOf(message.roomid) < 0) {
                socket.close();
                break;
            }
            //确认收到connect消息
            onConnect(socket, message);
            //发起方连接服务器
            if (message.state == 0) {
                console.info("==========> client a connect");
                break;
            }
            //接听方连接服务器
            console.info("==========> client b connect");
            //转发offer
            console.info("==========> send offer to client b");
            for (var i = 0; i < sockets.length; i++)
                if (sockets[i].state == 0 && sockets[i].roomid == message.roomid)
                    sendMessage(socket, {
                        type: "onoffer",
                        peerid: sockets[i].peerid,
                        offer: sockets[i].offer
                    });
            break;

        //收到offer
        case "offer":
            console.info("==========> get offer from a");
            socket.offer = message.offer;
            break;

        //收到answer
        case "answer":
            console.info("==========> get answer from b");
            socket.answer = message.answer;
            //转发answer
            console.info("==========> send answer to client a");
            for (let i = 0; i < sockets.length; i++)
                if (sockets[i].state == 0 && sockets[i].roomid == socket.roomid)
                    sendMessage(sockets[i], {
                        type: "onanswer",
                        peerid: socket.peerid,
                        answer: socket.answer
                    });
            //交换A与B的candidate
            //延时2秒,保证B端candidate全部发送
            setTimeout(() => {
                let socketA = null;
                let socketB = socket;
                for (let i = 0; i < sockets.length; i++)
                    if (sockets[i].state == 0 && sockets[i].roomid == socket.roomid)
                        socketA = sockets[i];
                console.info("==========> send candidates to b");
                for (let i in socketA.candidates)
                    sendMessage(socketB, {
                        type: "oncandidate",
                        peerid: socketA.peerid,
                        candidate: socketA.candidates[i]
                    });
                console.info("==========> send candidates to a");
                for (let i in socketB.candidates)
                    sendMessage(socketA, {
                        type: "oncandidate",
                        peerid: socketB.peerid,
                        candidate: socketB.candidates[i]
                    });
            }, 500);
            break;

        //收到candidate
        case "candidate":
            if (socket.state == 0)
                console.info("==========> get candidate from client a");
            else
                console.info("==========> get candidate from client b");
            socket.candidates.push(message.candidate);
            break;

        //有一方断开连接,通知其它方断开连接
        case "close":
            for (let i in sockets)
                if (sockets[i].roomid == socket.roomid)
                    socket.close();
            break;
    }
}

//确认收到Connect请求
function onConnect(socket, message) {
    //添加到socket和room数组
    socket.roomid = message.roomid;
    socket.peerid = message.peerid;
    socket.peerName = message.name;
    socket.state = message.state;
    socket.candidates = [];
    sockets.push(socket);
    if (rooms.indexOf(message.roomid) < 0)
        rooms.push(message.roomid);
    let msg = {
        type: "onconnect",
        peerid: message.peerid,
        roomid: message.roomid,
        state: socket.state,
    };
    sendMessage(socket, msg);
}

//发送Socket消息
function sendMessage(socket, message) {
    socket.send(JSON.stringify(message));
}


你可能感兴趣的:(javascript,android)