socket.io对IE8的支持

Posted 魔豆的BLOG<

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了socket.io对IE8的支持相关的知识,希望对你有一定的参考价值。

默认下载了最新版的socket.io,版本号是1.7.2,对IE8的支持不好,反正在IE8下收发消息都不行。在网上查了很多资料,都解决不了IE8的问题,崩溃。

 

最后用了一个大家比较认可的版本1.0.6,可以支持IE8:

卸载socket.io

npm uninstall socket.io

安装1.0.6版本的socket.io

npm install [email protected]

 

后面的一些版本没有一一的去试,下了一个1.3.7版本的,还是可以支持收发消息的,只是发现IE8在关闭窗口时,无法实时触发disconnect事件。

坑不只一个,除了socket.io的版本外,客户端代码,还需要在页面头部使用

<!DOCTYPE html>

才可以支持IE8。

 

下面是完整示例代码

服务端 app.js

var app = require(‘http‘).createServer(handler);
var io = require(‘socket.io‘)(app);
var fs = require(‘fs‘);
var url = require("url");

app.listen(80);

function handler (req, res) {
  var pathname = url.parse(req.url).pathname;
  if(pathname == "/") {
    pathname = "/index.html";
  }
  fs.readFile(__dirname + pathname, ‘utf-8‘,
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end(‘Error loading ‘ + pathname);
    }

    res.writeHead(200,{‘Content-Type‘:‘text/html;charset=utf-8‘});
    res.end(data);
  });
}

io.on(‘connection‘, function (socket) {
  console.log("Send message using: "+socket.conn.transport.name);                              
                              
  socket.on(‘message‘, function (data) {
    console.log(data);
    socket.broadcast.emit(‘cast‘, data);
  });

  socket.on(‘disconnect‘, function (data) {
    console.log(‘disconnect:‘ + data);
  });
});

 

客户端代码 index.html

<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>demo</title>
</head>

<body>


<script src="/socket.io/socket.io.js"></script>
<script src="jquery-1.11.3.min.js"></script>
<script>
  var socket = io.connect();
  
   socket.on(connect, function () {
        socket.on(cast, function (data) {
          $("#content").append("<br />" + data);
          });
   });

function send() {
    socket.emit(message, $("#msg").val());
}
</script>
<div id="content"></div>
<input type="text" name="msg" id="msg" />
<input type="button" name="Button" value="Button" onClick="send()">
</body>
</html>

 

以上是关于socket.io对IE8的支持的主要内容,如果未能解决你的问题,请参考以下文章

Socket.IO 和 IE8 - jsonp-polling 连接总是失败

兼容ie8,firefox,chrome浏览器的代码片段

websocket 与Socket.IO介绍

egg.js整合socket.io

socket.io客户端API

websocket兼容IE8