无需任何工具箱的 Matlab TCP/IP 命令服务器
以下函数(你需要放在 tcp_command_server.m 中)允许你通过 TCP/IP 远程执行 MATLAB 命令,而无需 Instrument Control Toolbox 或任何其他工具箱(tcpip 函数仅在 Instrument Control Toolbox 中可用,但底层 Java API 是普遍可用的)
注意: 仅用 Ctrl-C 停止不会立即停止服务器。按下 Ctrl-C 后,连接客户端以退出循环。
MATLAB 服务器
tcp_command_server.m
function tcp_command_server()
% Define port
port = 13972;
try
% Create Java ServerSocket
import java.net.*;
import java.io.*;
server_socket = ServerSocket(port);
server_socket.setSoTimeout(0); % No timeout
fprintf('Server started. Waiting for connections on port %d...\n', port);
fprintf('Press Ctrl+C to stop the server.\n');
% Wait for client connections
while true
try
% Blocks until a connection is established
client = server_socket.accept();
fprintf('Client connected: %s\n', client.getInetAddress().getHostAddress());
% Set up input and output streams
input_stream = BufferedReader(InputStreamReader(client.getInputStream()));
output_stream = PrintWriter(client.getOutputStream(), true);
% Read and execute commands from the client
while client.isConnected()
% Read command (blocking)
command = input_stream.readLine();
% If the client has closed the connection
if isempty(command)
break;
end
fprintf('Received command: %s\n', char(command));
try
% Execute command
result = evalc(char(command));
% Send back result
output_stream.println(['Result: ', result]);
catch e
% Handle errors
error_msg = ['Error: ', e.message];
fprintf('%s\n', error_msg);
output_stream.println(error_msg);
end
end
% Close connection
client.close();
fprintf('Client disconnected.\n');
catch e
if ~strcmp(e.identifier, 'MATLAB:Java:GenericException')
fprintf('Error processing client: %s\n', e.message);
end
end
end
catch e
fprintf('Server error: %s\n', e.message);
end
% Close server socket
if exist('server_socket', 'var') && ~isempty(server_socket)
server_socket.close();
end
fprintf('Server stopped.\n');
end客户端示例
此 Python 客户端连接到服务器并发送一组命令:
matlab_tcp_client.py
#!/usr/bin/env python3
import socket
import time
def connect_to_matlab_server(host='localhost', port=13972):
try:
# Create socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect to server
print(f"Establishing connection to {host}:{port}...")
client.connect((host, port))
print("Connection established!")
# Three MATLAB commands to send
commands = [
"disp('Hello from Python client!')",
"a = 5 + 10",
"disp(['The result is: ', num2str(a)])"
]
# Send each command and receive response
for cmd in commands:
print(f"\nSending command: {cmd}")
# Send command (with newline)
client.sendall((cmd + '\n').encode())
# Wait briefly and receive response
time.sleep(0.5)
response = client.recv(4096).decode().strip()
print(f"Response received: {response}")
print("\nClosing connection...")
except Exception as e:
print(f"Error: {e}")
finally:
# Close socket
client.close()
print("Connection closed.")
if __name__ == "__main__":
connect_to_matlab_server()示例输出
Python 输出:
matlab_tcp_client_output.txt
Establishing connection to localhost:13973...
Connection established!
Sending command: disp('Hello from Python client!')
Response received: Result: Hello from Python client!
Sending command: a = 5 + 10
Response received: Result:
a =
15
Sending command: disp(['The result is: ', num2str(a)])
Response received: Result: The result is: 15
Closing connection...
Connection closed.MATLAB 输出:
tcp_server_output.txt
Server started. Waiting for connections on port 13973...
Press Ctrl+C to stop the server.
Client connected: 127.0.0.1
Received command: disp('Hello from Python client!')
Received command: a = 5 + 10
Received command: disp(['The result is: ', num2str(a)])
Client disconnected.如何在后台启动它
此函数可用于使用定时器在后台运行 TCP 服务器。你可以调用此函数来启动服务器而不阻塞 MATLAB 命令窗口。
请注意,这不会阻塞命令窗口,但 Matlab 本质上仍然是单线程的,因此在服务器运行时,在同一 MATLAB 会话中运行 Simulink 仿真将无法工作。
start_tcp_server_background.m
% Start TCP server in the background using a timer
function start_tcp_server_background()
% Create timer
t = timer;
t.StartDelay = 1;
t.TimerFcn = @(~,~)tcp_command_server();
t.StopFcn = @(~,~)disp('TCP server stopped.');
t.ErrorFcn = @(~,~)disp('TCP server error occurred!');
% Start timer
start(t);
disp('TCP server started in the background.');
disp('Use "stop(timerfindall)" to stop all servers.');
endCheck out similar posts by category:
Matlab/Simulink
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow