Error occurred when communicating between MATLAB(Server) and Python(Client) via TCP/IP
古いコメントを表示
I'm using MATLAB R2021b now and intend to send some data to Python (of another device) via TCP/IP. And it's already be set that my MATLAB should work as a server while that Python treated as a client.
However, when using the newly created tcpserver() function in the instrument control toolbox, it's quite weird to find that the .Connected property is always 0 even though I'm pretty sure the connection has been established since I can receive the test request message sent from Python. And when I try to write the data and send it to Python, the following error occurred:
Failed to write from the server. A TCP/IP client must be connected to the server.
I have looked through all the possible suggestions online and found that someone had recommended to embed the write() function into a callback function https://www.mathworks.com/matlabcentral/answers/800901-interface-between-python-and-matlab-using-tcpserver
But unfortunately that dosen't meet my special request 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 functionality that those data could only be sent when the connection state changes.
Does anyone have better a solution to this problem? I'm waiting for your generous help!
code for MATLAB:
clc
clear
tcp_Server = tcpserver('127.0.0.1', 5001);
while true
if tcp_Server.NumBytesAvailable > 0
readData = read(tcp_Server, tcp_Server.NumBytesAvailable);
write(tcp_Server, "hello world");
break;
end
end
code for Python:
import socket
tcpSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serverIPPort = ('127.0.0.1', 5001)
tcpSocket.connect(serverIPPort)
# send request
msgSent = input("Request:")
tcpSocket.send(msgSent.encode("utf-8"))
# receive msg
tcpMsgReceived = tcpSocket.recv(1024)
print(tcpMsgReceived.decode("utf-8"))
tcpSocket.close()
採用された回答
その他の回答 (0 件)
カテゴリ
ヘルプ センター および File Exchange で Python Client Programming についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!