blib/lib/POE/Component/Client/WebSocket.pm

filter: Statementstmt 90.0% 18 / 20 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 7 / 7 Podpod n/a totaltotal 92.5% 25 / 27 CC 1 SCAR 0.4
CC
1
Cov
90%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
↑ Summary
1 package POE::Component::Client::WebSocket;
2  
3 1 ▶use 5.006;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 1 ▶use vars qw($VERSION);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 $VERSION = '0.1'; # NOTE - Should be #.### (three decimal places)
9  
10 1 ▶use Carp qw(carp croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
11 1 ▶use Errno qw(ETIMEDOUT ECONNRESET);
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 # Explicit use to import the parameter constants;
14 1 ▶use POE::Session;
Subroutine BEGIN: called CC=1 SCAR=2.6
15 use POE::Driver::SysRW;
16 use POE::Wheel::ReadWrite;
17 use POE::Wheel::SocketFactory;
18 use POE::Filter::Stackable;
19 use POE::Filter::SSL;
20 use POE::Filter::Stream;
21 use POE::Filter::HTTP::Parser;
22  
23 # Other various stuff
24 use URI::Split qw(uri_split);
25 use MIME::Base64;
26 use JSON::MaybeXS;
27 use Data::Dumper;
28  
29 # Crazy frame stuff
30 use Protocol::WebSocket::Frame;
31  
32 require HTTP::Request;
33  
34 # Global stuff for checks etc.
35 my $validOpts = {
36 types => {
37 'continuation' => 1,
38 'text' => 1,
39 'binary' => 1,
40 'ping' => 1,
41 'pong' => 1,
42 'close' => 1,
43 }
44 };
45  
46 =head1 NAME
47  
48 POE::Component::Client::WebSocket - A POE compatible websocket client
49  
50 =head1 VERSION
51  
52 Version 0.01
53  
54 =head1 WARNING: Work in progress! Only uploaded early for testing purposes!
55  
56 =head1 SYNOPSIS
57  
58 #!/usr/bin/env perl
59  
60 use warnings;
61 use strict;
62  
63 use POE qw(Component::Client::WebSocket);
64  
65 POE::Session->create(
66 inline_states => {
67 _start => sub {
68 my $ws = POE::Component::Client::WebSocket->new('wss://echo.websocket.org');
69 $ws->handler('connected','connected');
70 $ws->connect;
71  
72 $_[HEAP]->{ws} = $ws;
73  
74 $_[KERNEL]->yield("next")
75 },
76 next => sub {
77 $_[KERNEL]->delay(next => 1);
78 },
79 websocket_read => sub {
80 my ($kernel,$read) = @_[KERNEL,ARG0];
81  
82 print "Read: $read\n";
83 },
84 websocket_disconnected => sub {
85 warn "Disconnected";
86 },
87 connected => sub {
88 my $req = $_[ARG0];
89 },
90 websocket_handshake => sub {
91 my $res = $_[ARG0];
92  
93 $_[KERNEL]->post( $_[SENDER]->ID, 'send', 1234 );
94  
95 $_[HEAP]->{ws}->send(5678);
96 },
97 },
98 );
99  
100 POE::Kernel->run();
101 exit;
102  
103  
104 =head1 SUBROUTINES/METHODS
105  
106 =head2 new
107  
108 Create a new object
109  
110 =cut
111  
112 sub new {
113 my ($class,$uri) = @_;
114  
115 my $self = bless {
116 alias => __PACKAGE__,
117 session => 0,
118 }, $class;
119  
120 my ($scheme, $auth, $path, $query, $frag) = uri_split($uri);
121 my ($host,$port) = split(/:/,$auth);
122  
123 if (!$port) {
124 if (uc($scheme) eq 'WSS') { $port = 443 }
125 else { $port = 80 }
126 }
127  
128
129 my $key = "";
130 for (1..16) { $key .= rand(9) }
131  
132 $self->{session} = POE::Session->create(
133 package_states => [
134 $self => {
135 _start => '_start',
136 _stop => '_stop',
137 keep_alive => '_keep_alive',
138 connect => '_connect',
139 handler => '_handler',
140 origin => '_origin',
141 send => '_send',
142 socket_birth => '_socket_birth',
143 socket_death => '_socket_death',
144 socket_input => '_socket_input',
145 }
146 ],
147 heap => {
148 parent => POE::Kernel->get_active_session()->ID,
149 handlers => {
150 read => 'websocket_read',
151 connected => 'websocket_connected',
152 handshake => 'websocket_handshake',
153 disconnected => 'websocket_disconnected',
154 error => 'websocket_error',
155 },
156 uri => {
157 scheme => $scheme,
158 auth => $auth,
159 path => $path,
160 query => $query,
161 frag => $frag,
162 host => $host,
163 port => $port,
164 },
165 req => {
166 'origin' => 'http://'.$host,
167 'sec-websocket-key' => encode_base64($key),
168 },
169 _state => {
170 run => 1,
171 frame => Protocol::WebSocket::Frame->new,
172 },
173
174 }
175 );
176
177 $self->{id} = $self->{session}->ID;
178  
179 return $self;
180 }
181  
182 =head1 Internal functions (do not call these directly)
183  
184 =head2 _start
185  
186 Initial start handler
187  
188 =cut
189  
190 sub _start {
191 my ($kernel,$heap) = @_[KERNEL,HEAP];
192  
193 $kernel->yield('keep_alive');
194 }
195  
196 =head2 _stop
197  
198 Default stop handler for tidying things up
199  
200 =cut
201  
202 sub _stop {
203 }
204  
205 =head2 keep_alive
206  
207 Do not allow the module to stop running
208  
209 =cut
210  
211 sub _keep_alive {
212 my ($kernel,$heap) = @_[KERNEL,HEAP];
213  
214 return if (!$heap->{_state}->{run});
215  
216 $kernel->delay_add('keep_alive' => 1);
217 }
218  
219 =head2 _connect
220  
221 Initate a connect to the websocket
222  
223 =cut
224  
225 sub _connect {
226 my ($kernel,$heap) = @_[KERNEL,HEAP];
227  
228 $heap->{socket} = POE::Wheel::SocketFactory->new(
229 RemoteAddress => $heap->{uri}->{host},
230 RemotePort => $heap->{uri}->{port},
231 SuccessEvent => 'socket_birth',
232 FailureEvent => 'socket_death',
233 );}
234  
235 =head2 _handler
236  
237 Adjust the distribution map for handlers
238  
239 =cut
240  
241 sub _handler {
242 my ($kernel,$heap,$target,$destination) = @_[KERNEL,HEAP,ARG0,ARG1];
243  
244 $heap->{handlers}->{lc($target)} = $destination;
245 }
246  
247 =head2 _origin
248  
249 Change the origin used in the opening handshake
250  
251 =cut
252  
253 sub _origin {
254 my ($kernel,$heap,$target) = @_[KERNEL,HEAP,ARG0];
255  
256 $heap->{req}->{origin} = $target;
257 }
258  
259  
260 =head2 _send
261  
262 Send a frame encoded request to the server
263  
264 =cut
265  
266 sub _send {
267 my ($kernel,$heap,$data,$type,$fin,$masked) = @_[KERNEL,HEAP,ARG0,ARG1,ARG2,ARG3];
268  
269 $data = "" if (!$data);
270 $type = 'text' if ( (!$type) || (! $validOpts->{types}->{$type}) );
271 $fin = 1 if ((!defined $fin) || ($fin !~ m#^[01]$#));
272 $masked = 0 if ((!defined $masked) || ($fin !~ m#^[01]$#));
273  
274 my $frame = Protocol::WebSocket::Frame->new( buffer => $data, type => $type, fin => $fin, masked => $masked );
275 $heap->{wheel}->put($frame->to_bytes);
276 }
277  
278 =head2 _socket_birth
279  
280 Handle a socket when it connects to something
281  
282 =cut
283  
284 sub _socket_birth {
285 my ($kernel, $socket, $sockid, $heap) = @_[KERNEL, ARG0, ARG3, HEAP];
286  
287 if ( uc($heap->{uri}->{scheme}) eq 'WSS' ) {
288 $heap->{_state}->{sslfilter} = POE::Filter::SSL->new(client=>1);
289  
290 $heap->{filters}->{output} = POE::Filter::Stackable->new(Filters => [ $heap->{_state}->{sslfilter} ]);
291 $heap->{filters}->{input} = POE::Filter::Stackable->new(Filters => [ $heap->{_state}->{sslfilter} ]);
292 } else {
293 $heap->{filters}->{output} = POE::Filter::Stackable->new(Filters => []);
294 $heap->{filters}->{input} = POE::Filter::Stackable->new(Filters => []);
295 }
296
297 $heap->{filters}->{output}->push(POE::Filter::Stream->new());
298 $heap->{filters}->{input}->push(POE::Filter::Stream->new());
299  
300 $heap->{filters}->{output}->push( POE::Filter::HTTP::Parser->new( type => 'client' ) );
301 $heap->{filters}->{input}->push( POE::Filter::HTTP::Parser->new( type => 'client' ) );
302  
303  
304 $heap->{wheel} = POE::Wheel::ReadWrite->new(
305 Handle => $socket,
306 Driver => POE::Driver::SysRW->new(),
307 OutputFilter => $heap->{filters}->{output},
308 InputFilter => $heap->{filters}->{input},
309 InputEvent => 'socket_input',
310 ErrorEvent => 'socket_death',
311 );
312  
313 my $request = HTTP::Request->new(GET => '/');
314 $request->protocol('HTTP/1.1');
315 $request->header(
316 Upgrade => 'WebSocket',
317 Connection => 'Upgrade',
318 Host => $heap->{uri}->{host},
319 Origin => $heap->{req}->{origin},
320 'Sec-WebSocket-Key' => $heap->{req}->{'sec-websocket-key'},
321 'Sec-WebSocket-Protocol' => 'chat',
322 'Sec-WebSocket-Version' => 13,
323 );
324  
325 $heap->{wheel}->put($request);
326  
327 # Incase we want to investigate what we sent later.
328 $heap->{_state}->{req} = $request;
329  
330 $kernel->post( $heap->{parent}, $heap->{handlers}->{'connected'}, $request );
331 }
332  
333 =head2 _socket_death
334  
335 Handle a socket when it is disconnected
336  
337 =cut
338  
339 sub _socket_death { }
340  
341 =head2 _socket_input
342  
343 Read data from the socket
344  
345 =cut
346  
347 sub _socket_input {
348 my ($kernel,$heap,$buf) = @_[KERNEL,HEAP,ARG0];
349  
350 if (ref($buf) eq 'HTTP::Response') {
351 # Keep a copy of the response we got incase we want to have a look at it later
352 $heap->{_state}->{res} = $buf;
353  
354 # Send a copy of the handshake back to the users space
355 $kernel->post( $heap->{parent}, $heap->{handlers}->{'handshake'}, $buf );
356  
357 # Lets see if we can proceed
358 if ($buf->code() == 101) {
359 # Lets adjust our filters
360 $heap->{filters}->{output}->pop();
361 $heap->{filters}->{input}->pop();
362 }
363 } else {
364 $heap->{_state}->{frame}->append($buf);
365  
366 while (my $frame = $heap->{_state}->{frame}->next) { $kernel->post( $heap->{parent}, $heap->{handlers}->{read}, $frame ) }
367 }
368 }
369
370 =head1 OOP mappings from obj to POE
371  
372 =head2 connect
373  
374 Start the connection
375  
376 =cut
377  
378 sub connect { my $self = shift; POE::Kernel->post( $self->{session}->ID, 'connect', @_ ) }
379  
380 =head2 handler
381  
382 Adjust the handlers events are sent to
383  
384 =cut
385  
386 sub handler {
387 my ($self,$target,$destination) = @_;
388  
389 return if ( (!$target) || (!$destination) );
390  
391 POE::Kernel->post(
392 $self->{session}->ID,
393 'handler',
394 $target,
395 $destination
396 );
397 }
398  
399 =head2 origin
400  
401 Change the origin from the automatically generated one to something else
402  
403 =cut
404  
405 sub origin {
406 my ($self,$target) = @_;
407  
408 return if (!$target);
409  
410 POE::Kernel->post(
411 $self->{session}->ID,
412 'origin',
413 $target
414 );
415 }
416  
417 =head2 send
418  
419 Send data to the server, arguments are:
420 1: 'data' the information you want to send.
421 2: 'type' the type of information to send (default 'text')
422 3: 'fin' wether to send the 'fin' flag (default 1)
423 4: 'masked' wether the frame should be masked (default 0)
424  
425 =cut
426  
427 sub send {
428 my ($self,$data,$type,$fin,$masked) = @_;
429  
430 return if (!$data);
431  
432 POE::Kernel->post(
433 $self->{session}->ID,
434 'send',
435 $data,$type,$fin,$masked
436 );
437 }
438
439  
440 =head1 AUTHOR
441  
442 Paul G Webster, C<< <daemon at cpan.org> >>
443  
444 =head1 BUGS
445  
446 Please report any bugs or feature requests to C<bug-poe-component-client-websocket at rt.cpan.org>, or through
447 the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=POE-Component-Client-WebSocket>. I will be notified, and then you'll
448 automatically be notified of progress on your bug as I make changes.
449  
450  
451  
452  
453 =head1 SUPPORT
454  
455 You can find documentation for this module with the perldoc command.
456  
457 perldoc POE::Component::Client::WebSocket
458  
459  
460 You can also look for information at:
461  
462 =over 4
463  
464 =item * RT: CPAN's request tracker (report bugs here)
465  
466 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=POE-Component-Client-WebSocket>
467  
468 =item * AnnoCPAN: Annotated CPAN documentation
469  
470 L<http://annocpan.org/dist/POE-Component-Client-WebSocket>
471  
472 =item * CPAN Ratings
473  
474 L<http://cpanratings.perl.org/d/POE-Component-Client-WebSocket>
475  
476 =item * Search CPAN
477  
478 L<http://search.cpan.org/dist/POE-Component-Client-WebSocket/>
479  
480 =back
481  
482  
483 =head1 ACKNOWLEDGEMENTS
484  
485  
486 =head1 LICENSE AND COPYRIGHT
487  
488 Copyright 2016 Paul G Webster.
489  
490 This program is free software; you can redistribute it and/or modify it
491 under the terms of the the Artistic License (2.0). You may obtain a
492 copy of the full license at:
493  
494 L<http://www.perlfoundation.org/artistic_license_2_0>
495  
496 Any use, modification, and distribution of the Standard or Modified
497 Versions is governed by this Artistic License. By using, modifying or
498 distributing the Package, you accept this license. Do not use, modify,
499 or distribute the Package, if you do not accept this license.
500  
501 If your Modified Version has been derived from a Modified Version made
502 by someone other than you, you are nevertheless required to ensure that
503 your Modified Version complies with the requirements of this license.
504  
505 This license does not grant you the right to use any trademark, service
506 mark, tradename, or logo of the Copyright Holder.
507  
508 This license includes the non-exclusive, worldwide, free-of-charge
509 patent license to make, have made, use, offer to sell, sell, import and
510 otherwise transfer the Package with respect to any patent claims
511 licensable by the Copyright Holder that are necessarily infringed by the
512 Package. If you institute patent litigation (including a cross-claim or
513 counterclaim) against any party alleging that the Package constitutes
514 direct or contributory patent infringement, then this Artistic License
515 to you shall terminate on the date that such litigation is filed.
516  
517 Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER
518 AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES.
519 THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
520 PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY
521 YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR
522 CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR
523 CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE,
524 EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
525  
526  
527 =cut
528  
529 1; # End of POE::Component::Client::WebSocket
↑ Summary