Matlab TCP/IP command server without any toolboxes
The following function (which you need to put in tcp_command_server.m
) lets you remotely execute MATLAB commands via TCP/IP without requiring the Instrument Control Toolbox
or any other toolbox (the tcpip
function is only available in the Instrument Control Toolbox
, but the underlying Java API is universally available)
Note: Just stopping with Ctrl-C will not immediately stop the server. After you’ve hit Ctrl-C, connect with a client to get out of the loop.
MATLAB server
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
Client example
This Python client connects to the server and sends a bunch of commands:
#!/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()
Example output
Python output:
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 output:
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.
How to start it in the background
This function can be used to run the TCP server in the background using a timer. You can call this function to start the server without blocking the MATLAB command window.
Note that this will not block the command window but Matlab is still inherently single-threaded, so running a Simulink simulation in the same MATLAB session won’t work while the server is running.
% 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.');
end