700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > matlab用socket线程发送数据 使用Python Twisted和Autobahn从Matlab通过WebSocket发送JSON数据...

matlab用socket线程发送数据 使用Python Twisted和Autobahn从Matlab通过WebSocket发送JSON数据...

时间:2022-04-29 10:55:58

相关推荐

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 = mons.codec.binary.Base64

while true

tic;

packet = rand(100, 100);

json_packet = uint8(savejson('', packet));

compressed = press(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 = press(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运行,或者以另一种更快的方式解决这个问题?在

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。