我试图构建一个简单的websocket服务器,它加载一个包含一些tweet的文件(作为CSV),然后通过websocket将tweet的字符串发送到web浏览器。Here is a gist with the sample that I'm using for testing.这是Autobahn服务器组件(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()
{And>这里是web组件(^):
^{pr2}$当tweet到达浏览器时,UTF-8字符不能正确显示。如何修改这些简单的脚本以在浏览器中显示正确的UTF-8字符?在
而不是
<
尝试meta http-equiv="content-type" content="text/html; charset=UTF-8">
<;<
meta charset = utf-8>
如果您使用的是XHTML,那么写
<meta charset = utf-8 />
这对我有用:
注意事项:
另请注意:由于在这里解释的时间太长,Autobahn的
sendMessage
函数希望payload
已经是UTF8编码的,如果isBinary == False
。一个“普通”Python字符串是Unicode,它需要像上面那样编码成UTF8才能发送。在相关问题 更多 >
编程相关推荐