gpt4 book ai didi

python - 如何显示通过 websocket 发送的 UTF-8 字符?

转载 作者:行者123 更新时间:2023-11-28 18:45:18 25 4
gpt4 key购买 nike

我正在尝试构建一个简单的网络套接字服务器,该服务器加载一个包含一些推文的文件(作为 CSV),然后通过网络套接字将推文的字符串发送到网络浏览器。 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()

这是网络组件(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 字符?

最佳答案

这对我有用:

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|Python 0.7及以上
  • 我不确定你采样的 Gist 是否是正确的 UTF8 编码文件
  • 但是,“最后”伪推文是 10 倍“pi”,并且在浏览器中正确显示,所以它原则上有效..

另请注意:由于太长的原因无法在此处解释,如果 isBinary == False,Autobahn 的 sendMessage 函数预计 payload 已经是 UTF8 编码.一个“正常”的 Python 字符串是 Unicode,需要像上面那样编码成 UTF8 才能发送。

关于python - 如何显示通过 websocket 发送的 UTF-8 字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21389973/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com