]> Creatis software - CreaPhase.git/blob - octave_packages/ocs-0.1.3/utl/utl_sbn_server.m
Add a useful package (from Source forge) for octave
[CreaPhase.git] / octave_packages / ocs-0.1.3 / utl / utl_sbn_server.m
1 ## Copyright (C) 2006,2007,2008  Carlo de Falco            
2 ##
3 ## This file is part of:
4 ## OCS - A Circuit Simulator for Octave
5 ##
6 ## OCS is free software; you can redistribute it and/or modify
7 ## it under the terms of the GNU General Public License as published by
8 ## the Free Software Foundation.
9 ##
10 ## This program is distributed in the hope that it will be useful,
11 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
12 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 ## GNU General Public License for more details.
14 ##
15 ## You should have received a copy of the GNU General Public License
16 ## along with this program (see the file LICENSE); if not,
17 ## see <http://www.gnu.org/licenses/>.
18 ##
19 ## author: Carlo de Falco <cdf _AT_ users.sourceforge.net> 
20
21 ## -*- texinfo -*-
22 ## @deftypefn{Function File} {} utl_sbn_server(@var{port})
23 ## Listen for socket connections on port @var{port}, read a command @
24 ## and return the corresponding output to the socket. 
25 ## @end deftypefn
26
27 function utl_sbn_server (portnum)
28   
29   QUITMESSAGE    = "quit UTLsbnserver";
30   CONFIRMMESSAGE = "confirmed";
31
32   ## CREATE THE SOCKET AND WAIT FOR CONNECTIONS
33   s = socket(AF_INET, SOCK_STREAM, 0);
34   if s < 0
35     error("cannot create socket\n");
36   end
37   
38   if bind(s, portnum) < 0
39     error("bind failed\n");
40   end
41
42   if listen(s, 1) < 0
43     error("listen failed\n");
44   end
45
46   ##MAIN LOOP
47   while 1
48
49     ##ACCEPT CONNECTIONS
50     c = accept(s);
51     if c < 0
52       error("connection error")
53     end
54     
55     ## READ COMMANDS FROM THE SOCKET  
56     msg = readstring (c)
57     
58     ##IF CLIENT SENT SHUTDOWN MESSAGE EXIT
59     if strcmp (msg,QUITMESSAGE)
60       printf("client requested server shutdown, goodbye!\n");
61       disconnect(c); disconnect(s);
62       break
63     end
64     
65     ##EXECUTE COMMANDS FROM THE CLIENT
66     [A,B,C] = eval(msg);
67     
68     ##SEND OUTPUT TO THE CLIENT
69     str = [ sprintf("%17g ",A) "\n" sprintf("%17g ",B)...
70            "\n" sprintf("%17g ",C) "\n"]
71     
72     send(c,str);
73
74     ##END CONNECTION
75     disconnect(c);
76     
77   end
78
79   disconnect(s);
80 endfunction
81
82
83 function msg = readstring (c)
84   
85   BUFFER_SIZE = 255;
86
87   msg  = '';
88   read = BUFFER_SIZE;
89
90   while read >= BUFFER_SIZE
91     newmsg = char(recv(c, BUFFER_SIZE));
92     read = length(newmsg)
93     msg = [ msg newmsg];
94   end
95
96 endfunction