Sending information to MATLAB from Python via TCP

66 views (last 30 days)
I want to send data from Python to MATLAB every 10 seconds via TCP. The code I have works for the first iteration of the loop, but on the second iteration we reestablish the connection, yet the data fails to send.
The relevant Python code is:
import socket
import sys
import time
%Create a TCP/IP socket
i = 0 %loop counter
j=45.395 %data to be sent to MATLAB
while i < 1000:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(('localhost', 51001))
s.listen(1)
conn, addr = s.accept()
print(f"Connected by {addr}")
conn.sendall(bytes(str(j), 'ASCII'))
conn.close()
i+=1
j+=0.6
time.sleep(10)
The MATLAB code is
i=0;
while i < 1000
t = tcpclient('localhost', 51001);
output = read(t);
data = char(output(1:4));
pwrcmd = str2double(data);
fprintf('%f', pwrcmd);
clear t;
i = i+1;
pause(10)
end
and finally the output on the terminal is:
>python matlab_connect_test.py
Connected by ('127.0.0.1', 56010)
Connected by ('127.0.0.1', 56012)
The first thing I tried was to establish just one server-client connection, and send data every 10 seconds through that one connection, rather than reconnecting every 10 seconds. That was unsuccessful. For some reason even though the second connection is established, MATLAB never receives the second value of j, or any subsequent values. Any help would be very much appreciated.

Accepted Answer

sudobash
sudobash on 23 Aug 2022
Hi there!
This is the code that I tried which works:
python code:
import socket
import time
# Create a TCP / IP socket
i = 0 # loop counter
j = 45.395 # data to be sent to MATLAB
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(('localhost', 51001))
s.listen(1)
conn, addr = s.accept()
print(f"Connected: {conn, addr}")
while i < 3:
t = conn.sendall(f"{j}".encode())
i += 1
j += 0.6
time.sleep(5)
conn.close()
MATLAB code:
i=0;
t = tcpclient('localhost', 51001);
while i < 3
if t.NumBytesAvailable > 0
output = read(t);
data = char(output(1:4));
pwrcmd = str2double(data)
i = i+1;
end
end
clear t;
There is no need to create a new connection everytime you want to send data. Hope this solves your question.
  1 Comment
Ravi Achan
Ravi Achan on 23 Aug 2022
Thank you so much! This worked perfectly. For any other people who stumble upon this problem, I solved it prior to this answer by introducing a pause function in the MATLAB code, before the MATLAB read function. I think sudobash's solution is better as it specificallty waits until there is a message to be received. But pausing there also works as it gives the Python code a bit of time to send the message

Sign in to comment.

More Answers (0)

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!