How do I format data to send data using udp

조회 수: 3 (최근 30일)
Daan
Daan 2017년 4월 14일
답변: Nick 2017년 4월 14일
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))

답변 (1개)

Nick
Nick 2017년 4월 14일
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

카테고리

Help CenterFile Exchange에서 Call Python from MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by