我在使用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
发布于 2013-01-19 18:53:01
您的node.js文件(第一段代码)不是以UTF8编码保存的,node.js希望文件以UTF8保存。这取决于您的文本编辑器,但通常当您保存文件时,您应该能够选择一种编码。
https://stackoverflow.com/questions/14413355
复制相似问题