Matlab TCP/IP socket sender and receiver

The aim of this post is to provide a simple example of TCP/IP based socket communication with Matlab (done with Matlab R2012b). In this simple example, the sender is on a computer with IP address 192.168.0.10. The remote host (receiver) is on another computer with IP address 192.168.0.44. The communication is done on port 4013. Change these parameters according to your configuration. Check on both computer that the firewall is not blocking the port. Note that the receiver must be started first.

Sender

The following Matlab script sends 10 sockets spaced 500ms apart:

%% Matlab script for testing TCP/IP communication with matlab
%% This script is the sender part
%% Written by Philippe Lucidarme
%% https://www.lucidar.me/en/networks/matlab-tcp-ip-sender-and-receiver/

%% TCP/IP Sender

% Clear console and workspace
clc;
clear all;
close all;

% Configuration and connection
t = tcpip('192.168.0.44',4013);

% Open socket and wait before sending data
fopen(t);
pause(0.2);

% Send data every 500ms
for i=0:10    
    DataToSend=[i;i]
    fwrite(t,DataToSend);
    pause (0.5);
end

% Close and delete connection
fclose(t);
delete(t);

Receiver

The receiver read 10 sockets after configuring and connecting:

%% Matlab script for testing TCP/IP communication with matlab
%% This script is the receiver part
%% Written by Philippe Lucidarme
%% https://www.lucidar.me/en/networks/matlab-tcp-ip-sender-and-receiver/

%% TCP/IP Receiver

% Clear console and workspace
close all;
clear all;
clc;

% Configuration and connection
disp ('Receiver started');
t=tcpip('192.168.0.10', 4013,'NetworkRole','server');

% Wait for connection
disp('Waiting for connection');
fopen(t);
disp('Connection OK');

% Read data from the socket
for i=0:10
    DataReceived=fread(t,2)
end

Running

The receiver must be listening when the sender is launched otherwise the connection will not be successful. Note that this example also works on a single machine with two Matlab launched: change the IP address for 127.0.0.1 in both script. The receiver should display the following values:

Screenshot of the Matlab TCP/IP receiver

Download

Both scripts (sender and receiver) can be downloaded below:

matlab-tcp-ip-sender.m

matlab-tcp-ip-receiver.m


Last update : 06/11/2018