node.js 创建简单WebSocket接口

2019-02-23  本文已影响0人  书简_yu

官网: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);  // 打印 收到!  
}
上一篇 下一篇

猜你喜欢

热点阅读