Matlab TCP/IP-Befehlsserver ohne jegliche Toolboxes

Die folgende Funktion (die Sie in tcp_command_server.m einfügen müssen) ermöglicht es Ihnen, MATLAB-Befehle über TCP/IP remote auszuführen, ohne die Instrument Control Toolbox oder eine andere Toolbox zu benötigen (die tcpip-Funktion ist nur in der Instrument Control Toolbox verfügbar, aber die zugrunde liegende Java-API ist universell verfügbar)

Hinweis: Ein einfaches Stoppen mit Ctrl-C wird den Server nicht sofort stoppen. Nachdem Sie Ctrl-C gedrückt haben, verbinden Sie sich mit einem Client, um aus der Schleife herauszukommen.

MATLAB-Server

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

Client-Beispiel

Dieser Python-Client verbindet sich mit dem Server und sendet eine Reihe von Befehlen:

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()

Beispiel-Ausgabe

Python-Ausgabe:

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-Ausgabe:

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.

Wie man es im Hintergrund startet

Diese Funktion kann verwendet werden, um den TCP-Server im Hintergrund mit einem Timer auszuführen. Sie können diese Funktion aufrufen, um den Server zu starten, ohne das MATLAB-Befehlsfenster zu blockieren.

Beachten Sie, dass dies das Befehlsfenster nicht blockiert, aber Matlab ist immer noch inhärent single-threaded, sodass das Ausführen einer Simulink-Simulation in derselben MATLAB-Sitzung nicht funktioniert, während der Server läuft.

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.');
end

Check out similar posts by category: Matlab/Simulink