Interface between Python and Matlab using tcpserver

30 ビュー (過去 30 日間)
Felix Immanuel Oertel
Felix Immanuel Oertel 2021 年 4 月 13 日
回答済み: Kunal Kandhari 2021 年 6 月 20 日
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('', 1234)
while true
if server.NumBytesAvailable>0
data = read(server, 11, "string")
write(server, "Hello back!")
catch ME
clear server
The code for the Python client is the following:
import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.connect(('', 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?

回答 (1 件)

Kunal Kandhari
Kunal Kandhari 2021 年 6 月 20 日
Changing matlab code to following will work:
server = tcpserver('', 1234,"ConnectionChangedFcn",@connectionFcn)
function connectionFcn(src, ~)
if src.Connected
data = read(src, 11, "string")
write(src, "Hello back!")
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