File Exchange

image thumbnail

TCP/IP Socket Communications in MATLAB

version 1.0 (2.26 KB) by

A simple example TCP/IP server and client

4.83333
6 Ratings

39 Downloads

Updated

View License

Provides an example Server / Client written in MATLAB that utilises the ability to call Java inline to perform message communication using TCP/IP.

Importantly it does not require any pre-compiled DLLs or force you to compile some MEX c-files. Nor does it require any additional toolboxes Its all contained within the .m files.

To use the example:

- Start 2 instances of MATLAB
- in the first execute the following:
message = char(mod(1:1000, 255)+1);
server(message, 3000, 10)
- in the second execute the following:
data = client('localhost', 3000)

For more details see:
http://iheartmatlab.blogspot.com/2008/08/tcpip-socket-communications-in-matlab.html

Comments and Ratings (28)

ranjan

ranjan (view profile)

Hey Man! it works pretty well.... I have an issue.. I am trying to use ATMEGA164P+W5100 and matlab. I want matlab to be Client and the borad to be Server! Could you help me how to write a code which will send data to Server from Client..... My knowledge in Java is absolutely Zero :(

Richard Crozier

Seems to work well (on the provided example at least so far). However, to get it to compile on linux (using gcc 4.8.4) I had to convert all the C++ style single line comments starting '//' to C style /* */.

Narayani

Hi, I have a python script reading data from a USB device. I want to make this data continuously available to the model in Simulink. I tried TCP/IP but doesn't seem to work. How can I set them both up? Appreciate your suggestions.

Rodney Thomson

Rodney Thomson (view profile)

@nothing: It is probably best if you email me. Address in on my profile page

nothing

Thanks for reply!But I have got a problem that I can not receive data correctly by using the code you show me. The datas I received are always same.

Rodney Thomson

Rodney Thomson (view profile)

@nothing: You can either:
- Call readbyte enough times to get the data you want in a byte array, and then use the MATLAB command 'typecast' tonconvert values in the array to the desired type
- Call the DataInputStream methods: readDouble, readFloat, readShort, readInt etc, see http://docs.oracle.com/javase/6/docs/api/java/io/DataInputStream.html for more details

nothing

Thanks a lot!But what should I do if I want to receive numbers? Still readByte?

Rodney Thomson

Rodney Thomson (view profile)

@nothing: To do that, you need to do something like the following:

server.m:
% once you have the Socket (after a successful call to server_socket.accept) you would get a input stream and read as in client.m

output_socket = server_socket.accept;
input_stream = output_socket.getInputStream;
d_input_stream = DataInputStream(input_stream);

bytes_available = input_stream.available;
message = zeros(1, bytes_available, 'uint8');
for i = 1:bytes_available
message(i) = d_input_stream.readByte;
end

client.m:
% again, like above but in reverse. Once a connection is established you get an output stream and write
output_stream = input_socket.getOutputStream;
d_output_stream = DataOutputStream(output_stream);
d_output_stream.writeBytes(char(message));
d_output_stream.flush;

nothing

Thanks Rodney!!One more question:What should I do if I want to use server to receive data from client?

Rodney Thomson

Rodney Thomson (view profile)

@nothing : Of course, so long as TCP/IP is used over the interface!

Should be no different to localhost / ethernet / wifi. Just point it at the host and port.

nothing

Thanks Rodney!I have one question with it,can I use client.m to receive the data from WiFi?

Rodney Thomson

Rodney Thomson (view profile)

The next entry on the blog:
http://iheartmatlab.blogspot.com.au/2009/09/tcpip-socket-communications-in-matlab.html

Details using compiled Java class for pulling larger chunks of data from the socket at a time, returning them as MATLAB compatible arrays. It effectively wrappers the DataInputStream::read() method but returns an array, instead of taking an array by reference (which MATLAB cannot do)

kinor

kinor (view profile)

Hi Rodney,

thanks a lot for your fast reply.
The range of 1 -2s is what i achieved. Keeping the connections lets it drop to 0.1 s.
You say "Also the client.m code reads bytes 1 at a time which is very slow. See some of my other code examples on how to do this differently."
the link above just gives this one, where can I find them?

thanks a lot in advance
Kinor

Rodney Thomson

Rodney Thomson (view profile)

Kinor:
With your specific example, I'd expect latency on average of between 1 and 2 seconds.

That is because the server is setup and a client polls to connect for each 'ping' and 'pong'. That takes time.

What you should do is use the code inside client.m and server.m AS AN EXAMPLE and tailor it to suit your application.

IE it looks like you have bi-directional comms. You could setup one machine as server and another as client, then use the Java DataOutputStream/DataInputStream objects on both the client and server to both read and write data without re-establishing a connection each time.

Also the client.m code reads bytes 1 at a time which is very slow. See some of my other code examples on how to do this differently.

kinor

kinor (view profile)

Hi Rodney,

which latency do you achieve with your nice functions?

i.e.
first started,
session1:
data = client('localhost', 3000, -1)
message = '3001 message';
server(message, 3001, -1)

then,
session2:
tic
message = '3001 message';
server(message, 3000, -1)
data = client('localhost', 3001, -1)
toc

thanks for your fine functions kinor

Rodney Thomson

Rodney Thomson (view profile)

jawad - Yes you can. Simply run 2 instances of MATLAB and run 'client' in one, and 'server' in the other.

jawad

jawad (view profile)

Dear rodney thomson.
can we run the client.m and server.m on the single machine simultaneously.

Rodney Thomson

Rodney Thomson (view profile)

Sharath,

To receive data continuously, you will need to call read() many times after you have successfully connected to the server.

For high update scenarios, you may want to use the Java class approach (http://iheartmatlab.blogspot.com.au/2009/09/tcpip-socket-communications-in-matlab.html) to read the data in chunks as I doubt you would be able to keep up with 1000Hz data otherwise.

shaz

shaz (view profile)

if i am getting data continuosly say for every 1milli sec from server to client how do we handle this

Bebbe

Bebbe (view profile)

Hello Eric .. I read your problem and I need to communicate with clients and servers in bidirectional mode ... how did you solve your problem? I am not a java expert so I am a bit in trouble ...
sorry for my bad English ..
thanks a lot ..

Jens

Jens (view profile)

Hey Eric, my client have to send data to the server. Could you give me some help and tell me the way you solved the problem?

Eric

Eric (view profile)

I have solved my problem. Just write here to share with everyone. I also read a lot java documentations about socket. Finally i think this program is most simple and suitable for our use. We can change it to a bidirectional program according to our requests. This is example is very important. Thanks!

Eric

Eric (view profile)

Thanks s lot for Rodney effort.
But in my current project, I need to use socket to communicate with a phycial layer model. So I need to write and read from the model via socket. The example only gives one way direction communication, i.e. client read data from the server. So i hope to know: how does the client send data to server by socket ?
I copy some commands from the server:

output_stream = output_socket.getOutputStream;
d_output_stream = DataOutputStream(output_stream);

% output the data over the DataOutputStream
% Convert to stream of bytes
fprintf(1, 'Writing %d bytes\n', length(message))
d_output_stream.writeBytes(char(message));
d_output_stream.flush;

And apply these in sending data to server, but i found this doesn't work, i.e. the client can't send data to server. Could you please give me some help? Thanks very much.

Hello! I have one question.. Can i send wav files through this? Or this is only to send messages?
Thanks for your help

Rodney Thomson

Rodney Thomson (view profile)

Hi Maurizio,

Unfortunately the read(byte []) method will not work directly from within MATLAB. My thoughts as to why:

When you execute:
data = zeros(1, 100, 'char');
data_input_stream.read(data, 0, 100);
It supplies a COPY of the data array which would be populated. Unfortunately you don't have access to this. This requires pass-by-reference semantics which I don't think MATLAB currently support.

To get around this issue personally I've created helper Java classes to read blocks of data and RETURN the Byte array. This requires creating Java classes and compiling them.

Email me if you want some examples.

Rod

Giuela

Giuela (view profile)

It's very useful to build a simple network with MatLab, but in the example you read abyte in a loop. I've tried to read the buffer with the method read (byte [ ] b, int off, int len) of the class DataInputStream, but I don't find anything into the buffer b; the result of this method (the of bytes read) is correct! How can I pass the input buffer to the method?

Jorge Ramírez

Thanks, it is very easy to use and very useful.

Felipe Posada

Very useful, thank you.

MATLAB Release
MATLAB 7.0.4 (R14SP2)

Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.

» Watch video

Win prizes and improve your MATLAB skills

Play today