当前位置: 首页 > 工具软件 > ws.io > 使用案例 >

(精华)2020年7月8日 Node.js ws和websocket.io的使用

叶琦
2023-12-01

WS

客户端1

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link href="./main.css" rel="stylesheet">
</head>
<body>
    
<div id="wrapper" >
    <div id="txtConsole" class="main-header">
      
    </div>
    <div id="footer" class="footer">
        <input type='text' class="ipt" placeholder="请输入内容..." id="chatpIpt"/>
        <a href="javascript:;" class="btn" onclick="sendMsgHandler()">发送</a>       
    </div>
</div>

<script type="text/javascript" src='./ws.js'></script>
<script>
// 向服务端发送数据
function sendMsgHandler() {
    var elem =  document.getElementById('chatpIpt');
    var iptValue = elem.value;
    //发送信息到服务端
    // websocket.send({data:iptValue});
    websocket.send(JSON.stringify({
        name:'song',
        info:iptValue
    }));
    elem.value = "";
    elem.focus();
}
</script>
</body>
</html>

客户端2

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link href="./main.css" rel="stylesheet">
</head>
<body>
    
<div id="wrapper" >
    <div id="txtConsole" class="main-header">
      
    </div>
    <div id="footer" class="footer">
        <input type='text' class="ipt" placeholder="请输入内容..." id="chatpIpt"/>
        <a href="javascript:;" class="btn" onclick="sendMsgHandler()">发送</a>       
    </div>
</div>

<script type="text/javascript" src='./ws.js'></script>
<script>
    // 向服务端发送数据
    function sendMsgHandler() {
        var elem =  document.getElementById('chatpIpt');
        var iptValue = elem.value;
        //发送信息到服务端
        // websocket.send({data:iptValue});
        websocket.send(JSON.stringify({
            name:'laney',
            info:iptValue,
            time:Date.now()

        }));
        elem.value = "";
        elem.focus();
    }
    </script>
</body>
</html>

服务端

// native code
//必须服务端也是ws包发起
var websocket = new WebSocket('ws://localhost:8181');
 // 监听socket连接
websocket.addEventListener('open', function (evt) { 
    console.log('websocket open.')
    // websocket.send('oooo');
});
 // 监听socket消息,获取后端发来的信息
websocket.addEventListener('message', function (evt) { 
    var endData = JSON.parse(evt.data);
    console.log(evt.data); 
    console.log('Received data from '+endData.name+':'+evt.data);
 	// 如果需要把消息发送到所有用户,需要遍历
         /**
         * 把消息发送到所有的客户端
          * wss.clients获取所有链接的客户端
         */
        //   wss.clients.forEach(function each(client) {
        //      client.send(data);
        //   });
    showMessage(endData); 

});
 // 监听socket错误信息
 websocket.addEventListener('error', function (evt) {
    console.log('websocket error.')
})
 // socket关闭
websocket.addEventListener('close', function (evt) {
    console.log('websocket close.')
})

function showMessage(data) {
    
    var txtConsole = document.getElementById('txtConsole');
    var str = `<div class="show-message ${data.name=='laney'?'left':'right'}">
            <span class="name">${data.name}说:</span>
            <span class="info">${data.info}</span>
        </div>`;

    txtConsole.innerHTML +=str;
    
}

websocket.io

客户端

// Create SocketIO instance, connect
//io //Socket.io客户端对象
var socket = io.connect('ws://localhost:8083'); 

// Add a connect listener
socket.on('connect', function() {
    showMessage('Client has connected to the server!');
});

// Add a connect listener
socket.on('news', function(data) {
    var str = 'Received data from server. data : ' + JSON.stringify(data);
    debugger
    showMessage(str); 
});

// Add a disconnect listener
socket.on('disconnect', function() {
    showMessage('The client has disconnected');
});

// Sends a message to the server via sockets
function sendMessageToServer(msgData) {
    socket.emit('test_event', msgData);
}

function showMessage(str) {
    var txt = document.getElementById('txtConsole');
    txt.value = txt.value + '\n' + str;

}

// 向服务端发送数据
function sendMsgHandler() {
    var elem =  document.getElementById('chatpIpt');
    var iptValue = elem.value;
    sendMessageToServer({data : iptValue});
    elem.value = "";
    elem.focus();
}

服务端

//https://socket.io/get-started/chat/ 官网
// https://www.cnblogs.com/edwardloveyou/p/10625152.html 
// socket.io 与 ws对比
// https://blog.csdn.net/chenguohong88/article/details/81359307


// Websocket 研究 / Nodejs 模块选型对比
// https://cloud.tencent.com/developer/article/1005550

// Socket.io 快速搭建 和 注意事项
// https://www.jianshu.com/p/81ed0affe85a

// 安装:npm install socket.io   yarn add socket.io

var app = require('http').createServer(handler);
app.listen(8083,function(){
    console.log('8083端口开启成功!');
});

var socket = require('socket.io');
 //服务端的Socket.io对象
// var io = socket(app);
var io = socket.listen(app);

function handler(req, res) {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end('<h1>Hello Socket Lover!</h1>');
}

io.on('connection', function (socket) {
    // 只要连接成功,给客户端发送信息
    socket.emit('news', { data : 'server world----' });

    socket.on('test_event', function (data) {
        console.log('receive data from client. data : ' + JSON.stringify(data));

        var str = data.data + "(from server by " + new Date().getTime() + ")";
        socket.emit('news', { data : str});
        // 监听到test_event后,给客户端发送信息
    });

    socket.on('disconnect', function () {
        console.log('websocket close. -- server log');
    });
    
});

 类似资料: