Socket communication between a perl script and canvas


#!/usr/bin/perl -w
use Socket ;

sub ConnectToCanvas {
   my( $ck );
   $ck = socket( SOCK, PF_UNIX, SOCK_STREAM, 0 );
   if( ! $ck ){ print("nok socket\n"); } else { print("ok socket\n"); }
   $ck = connect( SOCK, sockaddr_un("/tmp/canvas.sock")) ;
   if( ! $ck ){ print("nok connect\n"); } else { print("ok connect\n"); }
   }

$msgbuf = "" ;

sub AppendMessage { my($msg) = @_ ;
   if( length($msgbuf) <= 0 ){ $msgbuf = $msg ; }
   else { $msgbuf = $msgbuf . "\n" . $msg ; }
   }

sub SendMessage {
   my( $ck );

   $ck = syswrite( SOCK, $msgbuf );
   if( ! $ck ){ print("syswrite returned $ck\n"); return ; }
   else { print("ok syswrite\n"); }
   $msgbuf = "" ;

   # if message was sent successfully, there will be a returnmessage :
   $ck = sysread( SOCK, $line, 100 );
   if( ! defined($ck) ){ print("nok sysread\n"); }
   elsif( $ck == 0 ){ print("sysread returned 0\n"); }
   else { print("read $ck bytes : $line\n"); }

   return( $line );
   }

# Notes
#
# Argument '100' to sysread() is size of read buffer ;
# When receiving event reports, you would need to use a larger buffer than this,
# and/or call sysread repeatedly until it returns less than buffersize.
#
# Replies are null-terminated.

ConnectToCanvas();
AppendMessage("drawline 55 10 55 100");
AppendMessage("setdrawcolor 255 0 128 0");
AppendMessage("flushlayer\nshowimobuf");
$reply = SendMessage();
print("reply = $reply\n");
AppendMessage("drawline 10 55 100 55");
AppendMessage("setdrawcolor 255 255 0 0");
AppendMessage("flushlayer\nshowimobuf");
$reply = SendMessage();
print("reply = $reply\n");