如何显示通过websocket发送的UTF8字符?

2024-10-01 11:21:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图构建一个简单的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字符?在


Tags: samplefromimportself服务器webfactory组件
2条回答

而不是<meta http-equiv="content-type" content="text/html; charset=UTF-8"><;尝试<meta charset = utf-8>
如果您使用的是XHTML,那么写<meta charset = utf-8 />

这对我有用:

from autobahn.twisted.websocket import WebSocketServerProtocol, \
                                       WebSocketServerFactory


class TweetStreamProtocol(WebSocketServerProtocol):

   def sendTweets(self):
      for line in open('gistfile1.txt').readlines():
         ## decode UTF8 encoded file
         data = line.decode('utf8').split(',')

         ## now operate on data using Python string functions ..

         ## encode and send payload
         payload = data[2].encode('utf8')
         self.sendMessage(payload)

      self.sendMessage((u"\u03C0"*10).encode("utf8"))

   def onMessage(self, payload, isBinary):
      if payload == "tweetme":
         self.sendTweets()



if __name__ == '__main__':

   import sys

   from twisted.python import log
   from twisted.internet import reactor

   log.startLogging(sys.stdout)

   factory = WebSocketServerFactory("ws://localhost:9000", debug = False)
   factory.protocol = TweetStreamProtocol

   reactor.listenTCP(9000, factory)
   reactor.run()

注意事项:

  • 以上代码适用于Autobahn|Python0.7及以上版本
  • 我不确定你的样本是否正确的UTF8编码文件
  • 但是,“最后一条”伪Tweet是10x“pi”,并且在浏览器中正确显示,因此 原则上是可行的。。在

另请注意:由于在这里解释的时间太长,Autobahn的sendMessage函数希望payload已经是UTF8编码的,如果isBinary == False。一个“普通”Python字符串是Unicode,它需要像上面那样编码成UTF8才能发送。在

相关问题 更多 >