MATLAB Answers

Interface between Python and Matlab using tcpserver

33 views (last 30 days)
Felix Immanuel Oertel
Felix Immanuel Oertel on 13 Apr 2021
Answered: Kunal Kandhari on 20 Jun 2021
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.

Community Treasure Hunt

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

Start Hunting!

Translated by