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
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.
s = whos('data')
s = name: 'data' size: [31 31] bytes: 7688 class: 'double' global: 0 sparse: 0 complex: 0 nesting: [1x1 struct] persistent: 0
Get the dimensions of the data array we will be transferring.
ans = 31 31
Get the number of bytes of data we will be transferring.
ans = 7688
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.
Open the server socket and wait indefinitely for a connection. This line will cause MATLAB to wait until an incoming connection is established.
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.
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.
tcpipClient = tcpip('127.0.0.1',55000,'NetworkRole','Client')
TCPIP Object : TCPIP-127.0.0.1 Communication Settings RemotePort: 55000 RemoteHost: 127.0.0.1 Terminator: 'LF' NetworkRole: client Communication State Status: closed RecordStatus: off Read/Write State TransferStatus: idle BytesAvailable: 0 ValuesReceived: 0 ValuesSent: 0
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.
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.
Open a TCPIP connection to the server.
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.
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);
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.
Get the MATLAB code
Published with MATLAB® 7.12
Comments are closed.
11 CommentsOldest to Newest
And for those who do not have the Instrument Control Toolbox, an excellent alternative to send data over networks is http://www.mathworks.com/matlabcentral/fileexchange/345-tcpudpip-toolbox-2-0-6
It is not rock-solid for maintaining connections over days and days, but for every-day use it is fast, simple and well-documented.
I have used it to build my own alternative to the Parallell Processing toolbox (One Matlab spawns other sessions and then hands out tasks via network communication) among other things.
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…
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…..!
If I understand your question correctly, you are trying to connect MATLAB to some other application. You should be able to do it in a manner very similar to the steps listed in the example above.
You need to know the following things before setting up the connection:
1. Is MATLAB a server or the client?
2. The IP address and communication port for the other application
Depending on the information above, you should be able to tweak the example above for your use.
In case of MATLAB being the server:
tcpipServer = tcpip('0.0.0.0',,'NetworkRole','Server');
In case of MATLAB being the client:
tcpipServer = tcpip('',,'NetworkRole','Client');
The MATLAB Central File Exchange entry (http://www.mathworks.com/matlabcentral/fileexchange/27290-collect-and-plot-data-from-a-tcpip-server-in-real-time) should help you in understanding the later configuration.
Hope this helps.
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.
The ‘NetworkRole’ property for TCPIP object was introduced only in release R2011a. TCPIP object as a server is not supported in R2009b.
Is there anyway to get a server socket to timeout if it doesn’t receive a connection within a period of time?
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.
Unfortunately there is no way for fopen(tcpipServer) to timeout. Currently the only way out is to use Ctl+C.
However, I will enter this enhancement request in our internal database for future consideration.
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.
My 2 cents.