美文网首页
node.js 创建简单WebSocket接口

node.js 创建简单WebSocket接口

作者: 书简_yu | 来源:发表于2019-02-23 20:14 被阅读0次

官网:ws

npm i ws -D

// server.js
let WebSocket = require('ws');

let instance = new WebSocket.Server({
    
    host: 'localhost',
    
    port: 3000
})

instance.on('connection', client => {
    
    client.on('message', data => {
        
        client.send('收到!');
    })
})

客户端

let webclient = new WebSocket('ws://loaclhost:3000');

// 发送消息
btn.onclick = function(){
      
      webclient.send('hello World, hi WebSocket')
}
// 接受消息
webclient.onmessage = function(message){

      console.log(message);  // 打印 收到!  
}

相关文章

网友评论

      本文标题:node.js 创建简单WebSocket接口

      本文链接:https://www.haomeiwen.com/subject/natmyqtx.html