[英]Send json with autobahn python
I am trying to send the json content from a url widh sendMessage to a client with. 我正在尝试将json内容从url widh sendMessage发送到客户端。
def broadcast(self):
response = urllib2.urlopen('http://localhost:8001/json?as_text=1')
data = json.load(response)
for c in self.clients:
c.sendMessage(data)
I get the error 我得到错误
File "myServer.py", line 63, in broadcast
c.sendMessage(data)
File "/Library/Python/2.7/site-packages/autobahn-0.6.3-py2.7.egg/autobahn /websocket.py", line 2605, in sendMessage
self.sendMessageHybi(payload, binary, payload_frag_size, sync, doNotCompress)
File "/Library/Python/2.7/site-packages/autobahn-0.6.3-py2.7.egg/autobahn /websocket.py", line 2671, in sendMessageHybi
self.sendFrame(opcode = opcode, payload = payload, sync = sync, rsv = 4 if sendCompressed else 0)
File "/Library/Python/2.7/site-packages/autobahn-0.6.3-py2.7.egg/autobahn/websocket.py", line 2161, in sendFrame
raw = ''.join([chr(b0), chr(b1), el, mv, plm])
exceptions.TypeError: sequence item 4: expected string, dict found
sendMessage
accepts a byte string or a unicode string - not a dictionary. sendMessage
接受字节字符串或unicode字符串-而不是字典。 This is because WebSockets are a transport for binary data and text data. 这是因为WebSockets是二进制数据和文本数据的传输。 It is not a transport for structured objects.
它不是结构化对象的传输。
You can send the JSON encoded form of the dictionary but you cannot send the dictionary itself: 您可以发送字典的JSON编码形式,但不能发送字典本身:
def broadcast(self):
response = urllib2.urlopen('http://localhost:8001/json?as_text=1')
for c in self.clients:
c.sendMessage(response)
Though note that you will actually want to use twisted.web.client
- not the blocking urllib2
: 但是请注意,您实际上将要使用
twisted.web.client
而不是urllib2
:
from twisted.internet import reactor
from twisted.web.client import Agent, readBody
agent = Agent(reactor)
def broadcast(self):
getting = agent.request(
b"GET", b"http://localhost:8001/json?as_text=1")
getting.addCallback(readBody)
def got(body):
for c in self.clients:
c.sendMessage(body)
getting.addCallback(got)
return getting
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.