express-ws是express的一个中间件,借助其我们可以在express中实现websocket的功能。

其github地址为:https://github.com/HenningM/express-ws

通过npm install express-ws可以安装。

服务端代码:

var express = require('express');
var app = express();
var expressWs = require('express-ws')(app);
var util = require('util');
app.use(express.static('./static'));
app.ws('/ws', function(ws, req) {
  util.inspect(ws);
  ws.on('message', function(msg) {
    console.log('_message');
    console.log(msg);
    ws.send('echo:' + msg);
  });
})
app.listen(3000);

客户端代码:

<!DOCTYPE html>
<html>
<head>
  <title>
    
  </title>
</head>
<body>
<script>
  var ws = new WebSocket('ws://localhost:3000/ws');
  ws.onmessage=function(e){
    console.log('_message');
    console.log(e.data);
  };
  ws.onerror=function(err){
    console.log('_error');
    console.log(err);
  };
  ws.onopen=function(){
    console.log('_connect')
  };
  ws.onclose=function(){
    console.log('_close');
  };

  ws.send('data');

</script>
</body>
</html>


更多推荐