Communicate Using TCP/IP Server Sockets
About Server Sockets
Support for server sockets is available using the tcpserver
function. This support is for a single remote connection.
You can use this connection to communicate between a client and MATLAB® or between two instances of MATLAB.
For example, you might collect data such as a waveform into one instance of MATLAB and then transfer it to another instance of MATLAB.
Note
The use of the server socket on either the client or server side should be done in accordance with the license agreement as it relates to your particular license option and activation type. If you have questions, you should consult with the administrator for your license or your legal department.
This is intended for use behind a firewall on a private network.
Communicate Between Two Instances of MATLAB
The following example shows how to connect two MATLAB sessions on the same computer, showing the example code for each
session. To use two different computers, replace "localhost"
with
the IP address of the server in the code for Session 2. Using 0.0.0.0 as the IP
address means that the server will accept the first machine that tries to connect.
To restrict the connections that will be accepted, replace
"0.0.0.0"
with the address of the client in the code for
Session 1.
Session 1: MATLAB Server
Accept a connection from any machine on port 30000.
server = tcpserver("0.0.0.0",30000)
server = TCPServer with properties: ServerAddress: "0.0.0.0" ServerPort: 30000 Connected: 0 ClientAddress: "" ClientPort: [] NumBytesAvailable: 0 Show all properties, functions
Session 2: MATLAB Client
This code is running on a second instance of MATLAB.
Create a client interface that connects to the server.
client = tcpclient("localhost",30000)
client = tcpclient with properties: Address: 'localhost' Port: 30000 NumBytesAvailable: 0 Show all properties, functions
Create a waveform and visualize it.
data = sin(1:64); plot(data);
Write the waveform to the client. Since the client is connected to the server, this data is available in the server session.
write(client,data,"double")
Session 1: MATLAB Server
Read the waveform and confirm it visually by plotting it.
data = read(server,server.NumBytesAvailable,"double");
plot(data);