javascript
matlab用socket线程发送数据,使用Python Twisted和Autobahn从Matlab通过WebSocket发送JSON数据...
我正在嘗試創建一個從Matlab到WebSocket流JSON幀的連接。我用下面的代碼測試了我的python安裝和twisted。在
工作實例
Matlab代碼
示例驅動程序代碼,它使用JSONlab工具箱將Matlab數據轉換為JSON格式,然后對數據進行Icompress和Base64編碼。因為我還沒有讓RPC工作,所以我使用命令行,我需要壓縮和Base64編碼來避免行長度和shell轉義問題。在clear all
close all
python = '/usr/local/bin/python'
bc = '/Users/palmerc/broadcast_client.py'
i = uint32(1)
encoder = org.apache.commons.codec.binary.Base64
while true
tic;
packet = rand(100, 100);
json_packet = uint8(savejson('', packet));
compressed = CompressLib.compress(json_packet);
b64 = char(encoder.encode(compressed));
message = sprintf('%s %s %s', python, bc, b64);
status = system(message);
i = i + 1;
toc;
end
廣播客戶端代碼
客戶端代碼有兩種調用方式。您可以通過命令行傳遞消息,也可以創建BroadcastClient實例并調用sendMessage。在
^{pr2}$
廣播服務器代碼
服務器使用TXJSONRPC、Twisted和Autobahn在7080上提供RPC客戶端,在8080上提供web客戶端,在9080上提供WebSocket。Autobahn Web Client對調試很有用,應該與服務器代碼放在同一個目錄中。在#!/usr/bin/env python
import sys
from twisted.internet import reactor
from twisted.python import log
from twisted.web.server import Site
from twisted.web.static import File
from txjsonrpc.web import jsonrpc
from autobahn.twisted.websocket import WebSocketServerFactory, \
WebSocketServerProtocol, \
listenWS
class BroadcastServerProtocol(WebSocketServerProtocol):
def onOpen(self):
self.factory.registerClient(self)
def onMessage(self, payload, isBinary):
if not isBinary:
message = "{} from {}".format(payload.decode('utf8'), self.peer)
self.factory.broadcastMessage(message)
def connectionLost(self, reason):
WebSocketServerProtocol.connectionLost(self, reason)
self.factory.unregisterClient(self)
class BroadcastServerFactory(WebSocketServerFactory):
"""
Simple broadcast server broadcasting any message it receives to all
currently connected clients.
"""
def __init__(self, url, debug=False, debugCodePaths=False):
WebSocketServerFactory.__init__(self, url, debug=debug, debugCodePaths=debugCodePaths)
self.clients = []
def registerClient(self, client):
if client not in self.clients:
print("registered client {}".format(client.peer))
self.clients.append(client)
def unregisterClient(self, client):
if client in self.clients:
print("unregistered client {}".format(client.peer))
self.clients.remove(client)
def broadcastMessage(self, message):
print("broadcasting message '{}' ..".format(message))
for client in self.clients:
client.sendMessage(message.encode('utf8'))
print("message sent to {}".format(client.peer))
class BroadcastPreparedServerFactory(BroadcastServerFactory):
"""
Functionally same as above, but optimized broadcast using
prepareMessage and sendPreparedMessage.
"""
def broadcastMessage(self, message):
print("broadcasting prepared message '{}' ..".format(message))
preparedMessage = self.prepareMessage(message.encode('utf8'), isBinary=False)
for client in self.clients:
client.sendPreparedMessage(preparedMessage)
print("prepared message sent to {}".format(client.peer))
class MatlabClient(jsonrpc.JSONRPC):
factory = None
def jsonrpc_broadcastMessage(self, message):
if self.factory is not None:
print self.factory.broadcastMessage(message)
if __name__ == '__main__':
if len(sys.argv) > 1 and sys.argv[1] == 'debug':
log.startLogging(sys.stdout)
debug = True
else:
debug = False
factory = BroadcastPreparedServerFactory(u"ws://127.0.0.1:9000",
debug=debug,
debugCodePaths=debug)
factory.protocol = BroadcastServerProtocol
listenWS(factory)
matlab = MatlabClient()
matlab.factory = factory
reactor.listenTCP(7080, Site(matlab))
webdir = File(".")
web = Site(webdir)
reactor.listenTCP(8080, web)
reactor.run()
問題-失敗的嘗試
首先要注意的是,如果在Matlab中使用python有困難,那么需要確保使用pyversion命令在系統上指向正確的python版本,并且可以使用pyversion('/path/to/python')來更正它
Matlab無法運行reactorclear all
close all
i = uint32(1)
while true
tic;
packet = rand(100, 100);
json_packet = uint8(savejson('', packet));
compressed = CompressLib.compress(json_packet);
b64 = char(encoder.encode(compressed));
bc.sendMessage(py.str(b64.'));
py.twisted.internet.reactor.run % This won't work.
i = i + 1;
toc;
end
Matlab POST
另一個嘗試涉及使用Matlab的webwrite來發布到服務器。結果表明,webwrite只需傳遞正確的weboptions,就可以將數據轉換為JSON。在options = weboptions('MediaType', 'application/json');
data = struct('Matrix', rand(100, 100));
webwrite(server, data, options);
這是有效的,但結果證明每個消息都很慢(約0.1秒)。我應該提到的是,矩陣并不是我發送的真實數據,真實數據序列化為每條消息280000字節,但這提供了一個合理的近似值。在
我怎樣才能調用bc.sendMessage以便它能夠正確地讓reactor運行,或者以另一種更快的方式解決這個問題?在
總結
以上是生活随笔為你收集整理的matlab用socket线程发送数据,使用Python Twisted和Autobahn从Matlab通过WebSocket发送JSON数据...的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 一招辨别真假Mesh路由-如何鉴别家用路
- 下一篇: 两个无线路由器的连接方法 二部路由器如何
