본문 바로가기

Enginius/Matlab

Socket communication between MATLAB and Python

MATLAB side

ccc

%% Socket communication with Python

% This is Server-side (so run this first).

ccc

 

% Open Socket

ip = '0.0.0.0';

port = 2002;

fprintf('Socket openning @%s:%d ... ',ip,port);

t = tcpip(ip, port, 'NetworkRole','server');

fopen(t);

fprintf('Opened.\n');

tick = 0;

 

while true

    % Read from socket (wait here)

    while t.BytesAvailable == 0, WAIT=true; end

    data = fread(t, t.BytesAvailable);

    string = char(data)';

    disp(string); % print-out

    % Read mat file

    mat_name2load = 'script/file_from_python.mat';

    l = load(mat_name2load); 

    disp(l); 

    

    % Save mat file

    mat_name2save = 'script/file_from_matlab.mat';

    x = l.x;

    y = l.y;

    save(mat_name2save,'x','y'); % save back

    % Send to socket

    tx_data = sprintf('[%d] This is from MATLAB.',tick);

    fwrite(t, tx_data);

    

    % terminate 

    tick = tick + 1;

    if tick >= 10, break; end

    pause(1e-0);

end

 

% Close

fclose(t);

fprintf('Closed.\n');



Python side

import socket,time

import scipy.io as sio

import numpy as np

print ("Packages loaded.")


TCP_IP = '0.0.0.0'

TCP_PORT = 2002

BUFFER_SIZE = 1024

print('Socket Information: %s:%d'%(TCP_IP,TCP_PORT))

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.connect((TCP_IP, TCP_PORT))

time.sleep(1e-3)


tick = 0

while True:

    # Save mat file with random matrices

    x = np.random.rand(100,10,10,3)

    y = np.random.rand(100,2)

    mat_name2load = 'file_from_python.mat'

    sio.savemat(mat_name2load, mdict={'x':x,'y':y})

    # Send to socket

    tx_data = '[%d] This is from Python.'%(tick)

    s.send(tx_data.encode())

    

    # Recieve from socket (wait here)

    rx_data = s.recv(BUFFER_SIZE).decode()

    if rx_data == '': # terminate 

        print ("Connection dropped.")

        break

    print (rx_data) # print-out

    # Load mat file and check the echoed matrices are the same. 

    mat_name2load = 'file_from_matlab.mat'

    l = sio.loadmat(mat_name2load)

    l_x,l_y = l['x'],l['y']

    print ("   x:%s y:%s"%(l_x.shape,l_y.shape))

    if np.array_equal(x,l_x) & np.array_equal(y,l_y):

        print ("   'x == l_x' and 'y == l_y' ")

    

    # pause

    tick += 1

    time.sleep(1e-3)

# Close socket 

s.close()

print ("Socket close.")