onsdag 1 april 2009

Octave sockets example

I tried to understand how Octaves (network) sockets work. The documentation is not very easy to understand.
As usual, an example is the easiest. I found one in the repository. See it at http://octave.svn.sourceforge.net/viewvc/octave/trunk/octave-forge/main/sockets/src/test_octave_sockets?revision=HEAD


Here is a minimal example:

In another window, set up a tcp server that outputs something you can read (install the netcat package if you do not already have it to get the nc command):
(while true; do sleep 1; date;done) |nc -l -p 9897

Then in octave:
client = socket(AF_INET, SOCK_STREAM, 0);
server_info = struct("addr", "127.0.0.1", "port", 9897);
rc = connect(client, server_info);
[msg_s, len_s] = recv(client,1000);
disp(len_s)
char(msg_s)

and there you go.


Edit: here is another example, this time setting up the listening socket within octave.
s=socket();
bind(s,12345);
a=listen(s,0)
b=accept(s)
len=10;
while true
[data,count]=recv(b,len)
fflush(stdout)
end


Connect to the port 12345 and try sending some data, and you will see the data in octave.