How do I format data to send data using udp

3 visualizaciones (últimos 30 días)
Daan
Daan el 14 de Abr. de 2017
Respondida: Nick el 14 de Abr. de 2017
I am trying to recreate python code (see below) using Matlab to communicate using a udp-protocol from the Instrument Control Toolbox (with basically no python experience). However I can't seem to figure out the data formatting corresponding to the python formatting. So far I have come to
u = udp('127.0.0.1',25000);
fopen(u)
str = sprintf('%f',0,0,0,0,0,0);
fprintf(u,str)
How do I send the same as using my python-file, or am I doing this completely wrong? I appreciate any help in advance.
Python - code:
import socket, struct, time, math
from math import pi
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(struct.pack("dddddd",0,0,0,0,0,0), ("127.0.0.1", 25000))

Respuestas (1)

Nick
Nick el 14 de Abr. de 2017
Hi try this. This code will send the str that you define to a python client listening on that port when you run the code. The matlab code will only send 1x but the Python code will stay listening
Matlab code:
%String to send
str = 'hello world'
u = udp('localhost',50000);
fopen(u)
%Send string over udp
fwrite(u,str)
fclose(u)
Python code UDP client: import socket
IP = "localhost"
PORT = 50000
sock = socket.socket(socket.AF_INET,
socket.SOCK_DGRAM) # UDP PROTOCOL
sock.bind((IP, PORT))
while True:
data, addr = sock.recvfrom(1024) # buffer = 1024 bytes
print "received message:", data

Categorías

Más información sobre Call Python from MATLAB en Help Center y File Exchange.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by