我无法使用 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 0.8.17 和 socket.io 0.9