为什么 server.on('upgrade'执行不到?
发布于 9 年前 作者 yakczh 4947 次浏览 最后一次编辑是 8 年前 来自 问答

参照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>
2 回复

端口不一致?

@xltank 不一定要同一个端口吧

回到顶部