CljPerl/SocketServer.pm untested

filter: Statementstmt 0.0% 0 / 65 Branchbran 0.0% 0 / 10 Conditioncond 0.0% 0 / 9 MC/DCmcdc 0.0% 0 / 6 Subroutinesub 0.0% 0 / 10 Podpod 0.0% 0 / 4 totaltotal 0.0% 0 / 104 CC 6 SCAR 17.2
CC
6
Cov
0%
socket_server
12.0
socket_send
6.0
socket_on_read
6.0
CRAP 5.6
1 package CljPerl::SocketServer;
2  
3 use strict;
4 use warnings;
5  
6  
7 our $VERSION = '0.10';
8  
9 use AnyEvent::Socket;
10 use AnyEvent::Handle;
11  
12 use Protocol::WebSocket::Handshake::Server;
13 use Protocol::WebSocket::Frame;
14  
15 sub socket_server {
16 my $host = shift;
17 my $port = shift;
18 my $sscb = shift;
19  
20 return AnyEvent::Socket::tcp_server $host, $port, sub {
21 my ($clsock, $host, $port) = @_;
22
23 my $hs = Protocol::WebSocket::Handshake::Server->new;
24 my $frame = Protocol::WebSocket::Frame->new;
25
26 my $hdl = AnyEvent::Handle->new(fh => $clsock);
27 $hdl->on_error(
28 sub {
29 my ($hdl, $fatal, $message) = @_;
30 #print "$message\n";
31 $hdl->destroy;
32 }
33 );
34 $hdl->on_eof(
35 sub {}
36 );
37 $hdl->{__on_read__} =
38 sub {
39 my $cb = shift;
40 sub {
41 my $hdl = shift;
42 my $chunk = $hdl->{rbuf};
43 $hdl->{rbuf} = undef;
44 if (!$hs->is_done) {
45 $hs->parse($chunk);
46 if ($hs->is_done) {
47 $hdl->push_write($hs->to_string);
48 return;
49 }
50 }
51 $frame->append($chunk);
52 while (my $message = $frame->next) {
53 &{$cb}($message);
54 # $hdl->push_write($frame->new($nmessage)->to_bytes);
55 };
56 }
57 };
58 $hdl->{__send__} =
59 sub {
60 my $msg = shift;
61 $hdl->push_write($frame->new($msg)->to_bytes);
62 #$hdl->push_write($hs->to_string);
63 };
64 &{$sscb}($hdl);
65 };
66 };
67  
68 sub socket_send {
69 my $socket = shift;
70 my $msg = shift;
71 if(defined $socket and ref($socket) ne "AnyEvent::Handle::destroyed"){
72 $socket->{__send__}->($msg);
73 };
74 };
75  
76 sub socket_on_read {
77 my $socket = shift;
78 my $cb = shift;
79 if(defined $socket and ref($socket) ne "AnyEvent::Handle::destroyed") {
80 $socket->on_read($socket->{__on_read__}->($cb));
81 };
82 };
83  
84 sub socket_destroy {
85 my $socket = shift;
86 if(defined $socket and ref($socket) ne "AnyEvent::Handle::destroyed") {
87 $socket->destroy;
88 };
89 };
90  
91 1;
92