我正在尝试构建一个简单的WebSocket服务器,它加载包含一些推文的文件(格式为CSV),然后通过WebSocket将推文字符串发送到Web浏览器。 这里是我用于测试的示例。 这是 Autobahn 服务器组件 (
当推文在浏览器中到达时,UTF-8字符无法正确显示。我该如何修改这些简单的脚本,以在浏览器中显示正确的UTF-8字符?
server.py
):import random
import time
from twisted.internet import reactor
from autobahn.websocket import WebSocketServerFactory, \
WebSocketServerProtocol, \
listenWS
f = open("C:/mypath/parsed_tweets_sample.csv")
class TweetStreamProtocol(WebSocketServerProtocol):
def sendTweet(self):
tweet = f.readline().split(",")[2]
self.sendMessage(tweet, binary=False)
def onMessage(self, msg, binary):
self.sendTweet()
if __name__ == '__main__':
factory = WebSocketServerFactory("ws://localhost:9000", debug = False)
factory.protocol = TweetStreamProtocol
listenWS(factory)
reactor.run()
以下是Web组件(index.html
):
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script type="text/javascript">
var ws = new WebSocket("ws://localhost:9000");
ws.onmessage = function(e) {
document.getElementById('msg').textContent = e.data; //unescape(encodeURIComponent(e.data));
console.log("Got echo: " + e.data);
}
</script>
</head>
<body>
<h3>Twitter Stream Visualization</h3>
<div id="msg"></div>
<button onclick='ws.send("tweetme");'>
Get Tweet
</button>
</body>
</html>
当推文在浏览器中到达时,UTF-8字符无法正确显示。我该如何修改这些简单的脚本,以在浏览器中显示正确的UTF-8字符?
self.sendMessage(u"\u03C0".encode("utf8"), binary = False)
,并检查浏览器中是否显示希腊字母"π"。 - oberstetself.sendMessage(tweet.encode("utf8"), binary=False)
,我会收到错误信息exceptions.UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 138: ordinal not in range(128)
。 - Clay