我正在尝试创建一个从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数据...相关推荐

  1. json模拟数据怎么用_在使用axios获取自己模拟的json数据是踩到的坑

    最近在使用Vue仿写一个网易云音乐的单页面应用,当页面布局什么的写完后,然后就准备用axios获取后台数据渲染页面了,当然,我自己写的,并没有后台,所以,我就自己写json文件,然后弄proxy代理什 ...

  2. ajax传json数据到后端struts,js与struts如何通过aja以json数据形式进行数据传输

    ajax已经是web开发的必选框架之一,而json更是在ajax通过解析xml来传输数据方面有了更好的发展,下面我就以自己做web开发的浅薄经验介绍一下js与struts 如何通过aja以json数据 ...

  3. python java通过socket交互数据 等到python服务端停止程序才能在java客户端看到数据的问题

    发送的数据如果不以\n   \r\n结尾 客户端就会一直以为数据还在发送,就不打印,  以为是"数据数据数据数据....."的形式 所以必须自己截断自己的数据形式 //我发送的数据 ...

  4. html js json数据解析后台数据包_如何将html解析为有关联的json数据?htmlparser2模块使用详解...

    上一篇文章我们介绍了一个html/xml解析器--htmlparser,这篇文章我们介绍另外一个解析模块htmlparser2,后者是对前者的重构,同时对前者的API做了部分兼容. 用法简介 安装 c ...

  5. python json有什么用_为什么要学习用Python解析JSON数据?

    "JSON(JavaScript Object Notation, JS 对象简谱) 是一种轻量级的数据交换格式.它基于 ECMAScript (欧洲计算机协会制定的js规范)的一个子集,采 ...

  6. python爬取京东手机数据_Python数据爬虫学习笔记(21)爬取京东商品JSON信息并解析...

    一.需求:有一个通过抓包得到的京东商品的JSON链接,解析该JSON内容,并提取出特定id的商品价格p,json内容如下: jQuery923933([{"op":"75 ...

  7. Python对json数据的提取

    JSON的全称是"JavaScript Object Notation",意思是JavaScript对象表示法,它是一种基于文本,独立于语言的轻量级数据交换格式.XML也是一种数据 ...

  8. 经济数据预测 | Python实现机器学习(MLP、XGBoost)金融市场预测

    经济数据预测 | Python实现机器学习(MLP.XGBoost)金融市场预测 目录 经济数据预测 | Python实现机器学习(MLP.XGBoost)金融市场预测 基本介绍 程序设计 MLP X ...

  9. android客户端从服务器端获取json数据并解析的实现代码

    2019独角兽企业重金招聘Python工程师标准>>> 首先客户端从服务器端获取json数据 1.利用HttpUrlConnection 代码如下: /** * 从指定的URL中获取 ...

最新文章

  1. DateGridView列的输出顺序反了
  2. 数组排序方法及C实现的总结
  3. linux下redis安装配置及redis常用命令(实战详细版)
  4. 数字图像处理,图像锐化算法的C++实现
  5. 高级版本VS打开低版本VS工程,无法调试的问题
  6. docker server 容器连接sql_Docker 容器的网络连接
  7. NIS认证管理域中的用户
  8. 如何将树莓派设置为WiFi热点
  9. 相机姿态估计(五)--DLS
  10. HDU 1811 Rank of Tetris(并查集+拓扑排序 非常经典)
  11. C语言动态链表实现KTV点歌系统
  12. 2022年中国游戏行业投融资发展报告
  13. vue的nxut框架生命周期触发两遍的问题
  14. uniapp 自定义头部 支持微信、百度、头条小程序
  15. 最简单的可拖拽窗口教程
  16. react 中 使用 Monaco Editor 编辑器
  17. 数据中心的端口密度该如何增加?
  18. python在线编程练习_有哪些在线编程练习网站?
  19. 工商管理如何利用计算机思维,论述工商管理人才素质的重要性
  20. html canvas 开发工具,基于js的html canvas工具包:cantool

热门文章

  1. Java合并pdf文件
  2. Redis--COW(Copy On Write)
  3. Apache Iceberg 快速入门
  4. IP地址、子网掩码、网关、路由器等知识积累
  5. 获取控制器 nextResponder的简单应用
  6. MySQL Study之--Percona Server版本
  7. 《深入理解Elasticsearch(原书第2版)》一2.2 查询改写
  8. hadoop文件系统与I/O流
  9. 【2011-04-06】SQL Server 2000 日志传送搭建
  10. 微软概述 Windows Server 2008 的定价、包装及授权