How do I format data to send data using udp
6 次查看(过去 30 天)
显示 更早的评论
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))
0 个评论
回答(1 个)
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Call Python from MATLAB 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!