1

我无法使用 nodejs 和 socket.io 将 utf-8 编码的字符串传递给客户端。我使用什么传输(websocket、flashsocket 或 xhr-polling)似乎并不重要。

代码非常简单明了:

服务器:

var app = require('http').createServer(handler)
, io = require('socket.io').listen(app,{log:false});

app.listen(80);

function handler (req, res) {
    fs.readFile(__dirname + '/index.html','utf-8',
        function (err, data) {
          if (err) {
            res.writeHead(500);
            return res.end('Error loading index.html');
          }
          var type="text/html";
          res.writeHead(200, {'Content-Type':type + "; charset=utf-8"});
          res.end(data,'utf8');
        });
}

io.sockets.on('connection', function (socket) {
    socket.emit('msg', { text: 'æøå' });//Here we send the utf-8 characters to the client
});

客户:

<!Doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta charset=utf-8 />
<script type="text/javascript" src="http://192.168.0.12/socket.io/socket.io.js" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">
  window.WEB_SOCKET_SWF_LOCATION = 'http://192.168.0.12/socket.io/static/flashsocket/WebSocketMain.swf';
  var socket = io.connect('http://192.168.0.12');
  socket.on('msg', function(data){alert(data.text);}); //here the data is recieved and put into the alert box
  ...
  ...

似乎数据始终是 UTF-8 双重编码,如下所示: 带有来自 nodejs 服务器的数据的客户端警报

我正在使用 nodejs 0.8.17 和 socket.io 0.9

4

1 回答 1

2

您的 node.js 文件(第一段代码)未以 UTF-8 编码保存,node.js 期望文件以 UTF-8 保存。这取决于您的文本编辑器,但通常当您保存文件时,您应该能够选择编码。

于 2013-01-19T10:53:01.117 回答