Interface between Python and Matlab using tcpserver

13 views (last 30 days)
I am currently trying to run an instance of matlab as a tcp server using the tcpserver function from the Instrument Control Toolbox. I want a python script that acts as the TCP client to connect to the matlab server, send it commands and get the results back via TCP. Here is a simple example of this connection, as I am trying to implement it:
server = tcpserver('127.0.0.1', 1234)
while true
if server.NumBytesAvailable>0
try
data = read(server, 11, "string")
write(server, "Hello back!")
catch ME
clear server
rethrow(ME)
end
end
end
The code for the Python client is the following:
import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.connect(('127.0.0.1', 1234))
print("Connection to server established!")
sock.sendall(b'Hello World')
data = sock.recv(1024)
print('Received', repr(data))
When I run the server and client, although Matlab receives the message from the Python client, I get the following error when it tries to send the answer:
data =
"Hello World"
Error using testserver (line 6)
Failed to write from the server. A TCP/IP client must be connected to the server.
Does anyone know why this happens and if there is a way to work around it?

Answers (1)

Kunal Kandhari
Kunal Kandhari on 20 Jun 2021
Changing matlab code to following will work:
server = tcpserver('127.0.0.1', 1234,"ConnectionChangedFcn",@connectionFcn)
function connectionFcn(src, ~)
if src.Connected
data = read(src, 11, "string")
write(src, "Hello back!")
end
end
It will not close the connection also infinite clients can connect to this server.
  1 Comment
文韬 王
文韬 王 on 5 Oct 2022
Hello! I have encountered the same problem described above. I have tried your code and it worked well.
But unfortunately I have some special demands since I want to send abundant real-time data through a long-term iteration and embed the whole thing in the appdesigner environment, that is to say, I cannot stand the limited functionality that those data could only be sent when the connection state changes. For more detail, please see https://www.mathworks.com/matlabcentral/answers/1818280-error-occurred-when-communicating-between-matlab-server-and-python-client-via-tcp-ip
As for my tricky situation, Do you have any other suggestions? Please lend me a hand.

Sign in to comment.

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!