04.node.js websocket

一、概念

Node.js WebSocket是一个用于建立实时双向通信的模块。WebSocket协议允许服务器与客户端之间进行全双工通信,其API使用了事件驱动和流式的方式。

二、客户端

 

复制代码
<!DOCTYPE html>
<html>
    <head>
        <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
    </head>
    <body>
        <button type="button" id="btn" >按钮</button>
        <input type="text" name="" id="demo" value="" />
        <div id="res">接收到的服务器端消息显示区域</div>
    </body>

    <script>
    // 打开一个 web socket,设定websocket服务器地址和端口
    var ws = new WebSocket("ws://127.0.0.1:3000");

    //开启连接open后客户端处理方法
    ws.onopen = function(){
    // Web Socket 已连接上,在页面中显示消息
    $('#res').html("当前客户端已经连接到websocket服务器");
    }

       // 点击按钮时给websocket服务器端发送消息
    $('#btn').click(function(){
        var value = $('#demo').val();
        ws.send(value);
    })

    // 接收消息后客户端处理方法
    ws.onmessage = function (evt) 
    { 
      console.log(evt.data);
      var obj = eval('('+evt.data+')');
      var html = $('#res').html();
      html = html +"<br />"+obj.data
      $('#res').html(html);
    };

    // 关闭websocket
    ws.onclose = function()
    { 
      // 关闭 websocket
      alert("连接已关闭..."); 
    };
    
    </script>
</html>
复制代码

 

三、服务端

 对于websocket开发,nodejs也有不少扩展第三方模块,例如,nodejs-websocket,node-websocket-server等。这里首先介绍使用nodejs-websocket来实现。

1、安装

npm install nodejs-websocket 

2、index.js代码

 

复制代码
var http = require("http"); 
var port = 9000
// 导入nodejs-websocket模块
const io = require('nodejs-websocket')
var user = 0

// 执行websocket处理连接方法
var wsserver = io.createServer(connection=>{
    console.log('new connection...')
    user++
    connection.nickname = "user"+user;
    connection.fd = "user"+user;
    var mes = {}
    mes.type = "enter";
    mes.data = connection.nickname + "进来了";
    broadcast(JSON.stringify(mes));

    //处理客户端发送过来的消息    
    connection.on("text",function(data){
        console.log("接收到的客户端消息:"+data);
        mes.type = "message"
        mes.data = connection.nickname+" 说:"+data;
        //connection.sendText(JSON.stringify(mes));
        broadcast(JSON.stringify(mes));
    })

    //监听关闭
    connection.on("close", function (code, reason) {
        mes.type = "leave"
        mes.data = connection.nickname+" 离开了 ";
        connection.sendText(JSON.stringify(mes));
        //console.log("Connection closed")
        broadcast(JSON.stringify(mes));
    })
    //监听异常
    connection.on("error",() => {
        console.log('服务异常关闭...')
    })    
    
}).listen(3000)

function broadcast(str){
    wsserver.connections.forEach(conn => {
        conn.sendText(str);
    });
}

/* 创建web服务  */
var server = http.createServer(function(req,res){
    res.writeHead(200,{'Content-type':'text/plain'})
    res.end('hello, world')
})

/* 监听方法 */
server.listen(port,function(){
    console.log('我的nodejs服务启动了,地址为127.0.0.1:'+port)
})
复制代码

 

 3、启动服务端

node index.js

4、打开服务端

 

5、客户端发送数据到服务端

 服务端接收到信息:

 

 

参考:https://developer.mozilla.org/zh-CN/docs/Web/API/WebSocket

https://www.npmjs.com/package/nodejs-websocket

https://zhuanlan.zhihu.com/p/350593517

 

posted @   ziff123  阅读(61)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示