为什么 server.on('upgrade'执行不到?
发布于 10 小时前 作者 yakczh 34 次浏览 来自 问答

参照https://github.com/faye/faye-websocket-node 上面的例子 server.js

var WebSocket = require('faye-websocket'),
fs=require('fs'),
    http      = require('http');

var server = http.createServer();

server.on('request',function(req,res){


  console.log('request');

   res.writeHeader(200, {"Content-Type": "text/html"});  
   var filename=__dirname+'/conn.html';
  fs.readFile(filename,'utf8',function (err,data)  {
//console.log(err); 

  res.end(data);
  })  

});


server.on('upgrade', function(request, socket, body) {
  if (WebSocket.isWebSocket(request)) {
    var ws = new WebSocket(request, socket, body);

    ws.on('message', function(event) {
      ws.send(event.data);
    });

    ws.on('close', function(event) {
      console.log('close', event.code, event.reason);
      ws = null;
    });
  }
});

server.listen(8000);

conn.html

<script type="text/javascript">

var wsServer = 'ws://localhost:8080';
			var ws = new WebSocket(wsServer);
			
			ws.onopen = function (e) {
			alert("Connected to WebSocket server.");
            }

</script>
回到顶部