This week's guest bloggers Ankit Desai and Vinod Cherian work on various aspects of using MATLAB to control instruments, make measurements with hardware, retrieve data from instruments,
and do custom analysis in MATLAB. In this post they talk about transferring data between two separate MATLAB sessions using
TCP/IP client-servers.

There are many cases where an operation needs to be performed in one MATLAB session and the data needs to be transferred to
a different machine for further analysis and visualization in MATLAB. Many of you have asked about transferring MATLAB arrays
between two MATLAB sessions on MATLAB Answers, the MATLAB newsgroup, and through technical support.

To show you an example of how this may be accomplished we've written an example that transfers the array of data required
to create an L-shaped membrane. The script uses the tcpip function in Instrument Control Toolbox. Specifically it uses the new NetworkRole property, which is a new property of tcpip objects in R2011a.

The example consists of two parts:

A MATLAB session on a server that needs to transfer its data out

A second MATLAB session on a client computer that retrieves and plots the data

Contents

Setting Up a MATLAB TCPIP Server Session

The MATLAB server session creates a data set to be transferred out, opens a TCP/IP server socket and waits for the client
to connect to it. When the connection is established, the data is written out to the socket.

Prepare the data we want to send over to the client MATLAB session. In this case our data is created by a call to the membrane function.

data = membrane(1);

Let us list details of the data set we want to transfer. We will use this information later to set up some parameters on the
server socket and in the client.

Start a TCP/IP server socket in MATLAB. By setting the IP address to '0.0.0.0' the server socket will accept connections on the specified port (arbitrarily chosen to be 55000 in our case) from any IP
address. You can restrict the TCP/IP server socket to only accept incoming connections from a specific IP address by explicitly
specifying the IP address. Note the new property NetworkRole.

tcpipServer = tcpip('0.0.0.0',55000,'NetworkRole','Server');

Set the OutputBufferSize property to a value large enough to hold the data. This is the first place where we use the output of the whos function, specifically the value of s.bytes.

set(tcpipServer,'OutputBufferSize',s.bytes);

Open the server socket and wait indefinitely for a connection. This line will cause MATLAB to wait until an incoming connection
is established.

fopen(tcpipServer);

Since the MATLAB server code is running in a separate MATLAB session than the client, you may notice the Busy status next to the MATLAB Start Button in the server session until the following commands have been executed. You may stop the MATLAB server socket creation and
break out of this busy state by using the Control-C key combination to close the server socket. Note that once you close the
server socket clients will no longer be able to connect to it until it has been re-opened.

Once the connection is made by the client, write the data out and close the server.

fwrite(tcpipServer,data(:),'double');
fclose(tcpipServer);

Setting Up the MATLAB Client Session

The MATLAB server session is running on a computer with a known IP address or hostname. In our case, this is the address '127.0.0.1'. The second MATLAB session that acts as the client application creates a TCP/IP client, connects to the server and retrieves
the data. Once retrieved, the data will be visualized in the client session.

Create a MATLAB client connection to our MATLAB server socket. Note the value of the NetworkRole property on the client. Also note that the port number of the client matches that selected for the server.

Set the InputBufferSize property so we have sufficient room to hold the data that will be sent to us by the server. The number 7688 is the number
of bytes in the data array. For more general purpose code, you can parametrize this code by using the value in s.bytes instead of the hard-coded value of 7688.

set(tcpipClient,'InputBufferSize',7688);

I will define a long value for the Timeout; the waiting time for any read or write operation to complete. Adjust this value to ensure that any data that is being transferred
to the client will be read back within the selected timeout.

set(tcpipClient,'Timeout',30);

Open a TCPIP connection to the server.

fopen(tcpipClient);

Read the data that is being written out on the server. Note that the data types need to be matched up on the client and server.
The number of double values to be read back from the server socket is 961. For more general purpose code, you may parametrize the second argument
using prod(s.size), for example.

rawData = fread(tcpipClient,961,'double');

Close the connection to the server once we've retrieved the data.

fclose(tcpipClient);

Reshape the data array and plot it. You can parametrize this by specifying s.size as the input to reshape instead of the hard-coded array size (31x31).

reshapedData = reshape(rawData,31,31);
surf(reshapedData);

Closing Notes

Note that this functionality is meant to be used behind a firewall or on a private network, and should be used in accordance
with the license agreement as it relates to your particular license option and activation type. For more information on using
MATLAB TCP/IP server sockets refer to the documentation.

We could see a number of uses of this functionality; an example being using MATLAB on an instrument used to gather data. Using
TCP/IP server sockets in MATLAB it is now possible to transfer the data out, without the need for files, to a remote computer
for further analysis and visualization in MATLAB.

How do you see this functionality being used? Post your responses here.

Thanks, didn’t know about the new NetworkRole functionality. I’va also been using PNet for TCP/UDP communication between Matlab instances so far.

One critical block, and something Mathworks could fix easily – what happens when I want to send matlab objects, there is no way to serialize objects except save to disk, read bytes from disk and send them; write to disk on the server and then read the resultant mat file. This is very slow!!!

I also think the TCP communication should be part of Matlab core, this is useful for so much more than controlling external instruments (as your post shows)!

hi….i have some questions that this passage coulden`t helep me…
so…
let`s answer me…
in the case ofconnection to matlab by some diffrenet application …
i need to make that imagin real…
I`ve rote a programm…that need to the mass calculating so I realy haveto work by matlab…
i can not connetct this to any vay…
clear the way for me show me how I can connect this to each other…..!

I’m using the Instrument control toolboax with MATLAB R2009b, the “NetworkRole” property does not exist, how can start the tcpip on the server. I want to have a TCPIP senssion between to MATLAB sessions.

Is there a way to set a timeout for a the server connection so that if it doesn’t receive a connection within a certain time the process can continue? Right now once fopen(tcpipServer); is issued the only way out is ctl-C.

I would like to expand on the idea of communication between Matlab and other applications. (As referred to in response #4)
Instead of transferring data between applications, I would like to have tcl tell Matlab to run a script. Is that possible? Thank you.

I agree with another poster – that tcp/ip functionality should be built into MATLAB core.

Moreover, I think the ability to do this at this low level is great, but why must it always be so hard? Here’s the level at which I think it should work:

One should be able to list all instances of MATLAB running on the local network (or specify an IP address for a specific computer). Then one should be able to select an instance and “send” it any MATLAB variable/matrix/object/structure/cellarray/etc. The receiver should be able to automatically accept objects sent from known senders or should be prompted for acceptance. All the details regarding the connection should be completely transparent. It should just work.

Another feature should include the ability to share a workspace between two instances of MATLAB. In that way, users collaborating on a data set could work simultaneously and see each other’s results. One could even select which plots should show up on the other person’s workstation.