view release on metacpan or search on metacpan
# =========================================================================
# THIS FILE IS AUTOMATICALLY GENERATED BY MINILLA.
# DO NOT EDIT DIRECTLY.
# =========================================================================
use 5.008_001;
use strict;
use warnings;
use utf8;
use Module::Build;
use File::Basename;
use File::Spec;
use CPAN::Meta;
use CPAN::Meta::Prereqs;
my %args = (
license => 'perl',
dynamic_config => 0,
configure_requires => {
'Module::Build' => 0.38,
},
name => 'PocketIO',
module_name => 'PocketIO',
allow_pureperl => 0,
script_files => [glob('script/*'), glob('bin/*')],
c_source => [qw()],
PL_files => {},
test_files => ((-d '.git' || $ENV{RELEASE_TESTING}) && -d 'xt') ? 't/ xt/' : 't/',
recursive_test_files => 1,
);
if (-d 'share') {
$args{share_dir} = 'share';
}
my $builder = Module::Build->subclass(
class => 'MyBuilder',
code => q{
sub ACTION_distmeta {
die "Do not run distmeta. Install Minilla and `minil install` instead.\n";
}
sub ACTION_installdeps {
die "Do not run installdeps. Run `cpanm --installdeps .` instead.\n";
}
}
)->new(%args);
$builder->create_build_script();
my $mbmeta = CPAN::Meta->load_file('MYMETA.json');
my $meta = CPAN::Meta->load_file('META.json');
my $prereqs_hash = CPAN::Meta::Prereqs->new(
$meta->prereqs
)->with_merged_prereqs(
CPAN::Meta::Prereqs->new($mbmeta->prereqs)
)->as_string_hash;
my $mymeta = CPAN::Meta->new(
{
%{$meta->as_struct},
prereqs => $prereqs_hash
}
);
print "Merging cpanfile prereqs to MYMETA.yml\n";
$mymeta->save('MYMETA.yml', { version => 1.4 });
print "Merging cpanfile prereqs to MYMETA.json\n";
$mymeta->save('MYMETA.json', { version => 2 });
Revision history for perl module PocketIO
0.17 2014-01-07T20:29:26Z
- just meta files update
0.16 2013-10-25T16:55:13Z
- Fixed bug when attempting to broadcast->send (mvgrimes)
- support method other than 'run' (tokubass)
0.15 2012-12-30
- Fixed room stringification problem (Peter Stuifzand)
- Skip hanging test on windows
0.14 2012-06-05
- Fixed exception handling bugs (Jason May)
- Provide the status code when throwing a websocket exception (Jason May)
- Added room support (Michael FiG)
0.12 2012-01-25
- Fixed test requirements
0.11 2012-01-24
- Fixed modules requirements
0.10 2012-01-22
- Plack::Request is not required
- Twiggy is not required for testing
- Extracted SocketIO protocol into a separated distribution
- Return raw object but wrap exceptions middelware on the fly
- Fixed on_disconnect callback
0.009008 2011-12-06
- Fixed websocket test
0.009007 2011-12-03
- Fixed CPAN dist
0.009006 2011-12-02
- Made message parsing more robust. Closes #GH-10
- Socket emit should emit client event not server
- Use exceptions
- Updated socket.io.js in example
- Increased connection timeout
- Require Protocol::WebSocket 0.9.5
- Increased connection timeout to 30s
0.009005 2011-09-23
- CPAN release
- Redis pool backend
- Socket.IO 0.8 version support
0.009004 2011-05-12
- Renamed to PocketIO
- Implemented as a Plack app instead of middleware
- Fixed UTF issues
0.009003 2011-04-09
- It is possible to pass class name or instance and method instead of inline
handler
- Added heartbeat to WebSockets too
0.009002 2011-03-29
- Fixed live tests
0.009001 2011-03-28
- Fixed dependencies list
0.009000 2011-03-16
- Initial release
This software is copyright (c) 2013 by Viacheslav Tykhanovskyi
<viacheslav.t@gmail.com>.
This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.
Terms of the Perl programming language system itself
a) the GNU General Public License as published by the Free
Software Foundation; either version 1, or (at your option) any
later version, or
b) the "Artistic License"
--- The GNU General Public License, Version 1, February 1989 ---
This software is copyright (c) 2013 by Viacheslav Tykhanovskyi
<viacheslav.t@gmail.com>.
This is free software, licensed under:
The GNU General Public License, Version 1, February 1989
GNU GENERAL PUBLIC LICENSE
Version 1, February 1989
Copyright (C) 1989 Free Software Foundation, Inc.
51 Franklin St, Suite 500, Boston, MA 02110-1335 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The license agreements of most software companies try to keep users
at the mercy of those companies. By contrast, our General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. The
General Public License applies to the Free Software Foundation's
software and to any other program whose authors commit to using it.
You can use it for your programs, too.
When we speak of free software, we are referring to freedom, not
price. Specifically, the General Public License is designed to make
sure that you have the freedom to give away or sell copies of free
software, that you receive source code or can get it if you want it,
that you can change the software or use pieces of it in new free
programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of a such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must tell them their rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any program or other work which
contains a notice placed by the copyright holder saying it may be
distributed under the terms of this General Public License. The
"Program", below, refers to any such program or work, and a "work based
on the Program" means either the Program or any work containing the
Program or a portion of it, either verbatim or with modifications. Each
licensee is addressed as "you".
1. You may copy and distribute verbatim copies of the Program's source
code as you receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice and
disclaimer of warranty; keep intact all the notices that refer to this
General Public License and to the absence of any warranty; and give any
other recipients of the Program a copy of this General Public License
along with the Program. You may charge a fee for the physical act of
transferring a copy.
2. You may modify your copy or copies of the Program or any portion of
it, and copy and distribute such modifications under the terms of Paragraph
1 above, provided that you also do the following:
a) cause the modified files to carry prominent notices stating that
you changed the files and the date of any change; and
b) cause the whole of any work that you distribute or publish, that
in whole or in part contains the Program or any part thereof, either
with or without modifications, to be licensed at no charge to all
third parties under the terms of this General Public License (except
that you may choose to grant warranty protection to some or all
third parties, at your option).
c) If the modified program normally reads commands interactively when
run, you must cause it, when started running for such interactive use
in the simplest and most usual way, to print or display an
announcement including an appropriate copyright notice and a notice
that there is no warranty (or else, saying that you provide a
warranty) and that users may redistribute the program under these
conditions, and telling the user how to view a copy of this General
Public License.
d) You may charge a fee for the physical act of transferring a
copy, and you may at your option offer warranty protection in
exchange for a fee.
Mere aggregation of another independent work with the Program (or its
derivative) on a volume of a storage or distribution medium does not bring
the other work under the scope of these terms.
3. You may copy and distribute the Program (or a portion or derivative of
it, under Paragraph 2) in object code or executable form under the terms of
Paragraphs 1 and 2 above provided that you also do one of the following:
a) accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of
Paragraphs 1 and 2 above; or,
b) accompany it with a written offer, valid for at least three
years, to give any third party free (except for a nominal charge
for the cost of distribution) a complete machine-readable copy of the
corresponding source code, to be distributed under the terms of
Paragraphs 1 and 2 above; or,
c) accompany it with the information you received as to where the
corresponding source code may be obtained. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form alone.)
Source code for a work means the preferred form of the work for making
modifications to it. For an executable file, complete source code means
all the source code for all modules it contains; but, as a special
exception, it need not include source code for modules which are standard
libraries that accompany the operating system on which the executable
file runs, or for standard header files or definitions files that
accompany that operating system.
4. You may not copy, modify, sublicense, distribute or transfer the
Program except as expressly provided under this General Public License.
Any attempt otherwise to copy, modify, sublicense, distribute or transfer
the Program is void, and will automatically terminate your rights to use
the Program under this License. However, parties who have received
copies, or rights to use copies, from you under this General Public
License will not have their licenses terminated so long as such parties
remain in full compliance.
5. By copying, distributing or modifying the Program (or any work based
on the Program) you indicate your acceptance of this license to do so,
and all its terms and conditions.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the original
licensor to copy, distribute or modify the Program subject to these
terms and conditions. You may not impose any further restrictions on the
recipients' exercise of the rights granted herein.
7. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of the license which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
the license, you may choose any version ever published by the Free Software
Foundation.
8. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
9. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
10. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
Appendix: How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to humanity, the best way to achieve this is to make it
free software which everyone can redistribute and change under these
terms.
To do so, attach the following notices to the program. It is safest to
attach them to the start of each source file to most effectively convey
the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) 19yy <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 1, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) 19xx name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the
appropriate parts of the General Public License. Of course, the
commands you use may be called something other than `show w' and `show
c'; they could even be mouse-clicks or menu items--whatever suits your
program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
program `Gnomovision' (a program to direct compilers to make passes
at assemblers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
That's all there is to it!
--- The Artistic License 1.0 ---
This software is copyright (c) 2013 by Viacheslav Tykhanovskyi
<viacheslav.t@gmail.com>.
This is free software, licensed under:
The Artistic License 1.0
The Artistic License
Preamble
The intent of this document is to state the conditions under which a Package
may be copied, such that the Copyright Holder maintains some semblance of
artistic control over the development of the package, while giving the users of
the package the right to use and distribute the Package in a more-or-less
customary fashion, plus the right to make reasonable modifications.
Definitions:
- "Package" refers to the collection of files distributed by the Copyright
Holder, and derivatives of that collection of files created through
textual modification.
- "Standard Version" refers to such a Package if it has not been modified,
or has been modified in accordance with the wishes of the Copyright
Holder.
- "Copyright Holder" is whoever is named in the copyright or copyrights for
the package.
- "You" is you, if you're thinking about copying or distributing this Package.
- "Reasonable copying fee" is whatever you can justify on the basis of media
cost, duplication charges, time of people involved, and so on. (You will
not be required to justify it to the Copyright Holder, but only to the
computing community at large as a market that must bear the fee.)
- "Freely Available" means that no fee is charged for the item itself, though
there may be fees involved in handling the item. It also means that
recipients of the item may redistribute it under the same conditions they
received it.
1. You may make and give away verbatim copies of the source form of the
Standard Version of this Package without restriction, provided that you
duplicate all of the original copyright notices and associated disclaimers.
2. You may apply bug fixes, portability fixes and other modifications derived
from the Public Domain or from the Copyright Holder. A Package modified in such
a way shall still be considered the Standard Version.
3. You may otherwise modify your copy of this Package in any way, provided that
you insert a prominent notice in each changed file stating how and when you
changed that file, and provided that you do at least ONE of the following:
a) place your modifications in the Public Domain or otherwise make them
Freely Available, such as by posting said modifications to Usenet or an
equivalent medium, or placing the modifications on a major archive site
such as ftp.uu.net, or by allowing the Copyright Holder to include your
modifications in the Standard Version of the Package.
b) use the modified Package only within your corporation or organization.
c) rename any non-standard executables so the names do not conflict with
standard executables, which must also be provided, and provide a separate
manual page for each non-standard executable that clearly documents how it
differs from the Standard Version.
d) make other distribution arrangements with the Copyright Holder.
4. You may distribute the programs of this Package in object code or executable
form, provided that you do at least ONE of the following:
a) distribute a Standard Version of the executables and library files,
together with instructions (in the manual page or equivalent) on where to
get the Standard Version.
b) accompany the distribution with the machine-readable source of the Package
with your modifications.
c) accompany any non-standard executables with their corresponding Standard
Version executables, giving the non-standard executables non-standard
names, and clearly documenting the differences in manual pages (or
equivalent), together with instructions on where to get the Standard
Version.
d) make other distribution arrangements with the Copyright Holder.
5. You may charge a reasonable copying fee for any distribution of this
Package. You may charge any fee you choose for support of this Package. You
may not charge a fee for this Package itself. However, you may distribute this
Package in aggregate with other (possibly commercial) programs as part of a
larger (possibly commercial) software distribution provided that you do not
advertise this Package as a product of your own.
6. The scripts and library files supplied as input to or produced as output
from the programs of this Package do not automatically fall under the copyright
of this Package, but belong to whomever generated them, and may be sold
commercially, and may be aggregated with this Package.
7. C or perl subroutines supplied by you and linked into this Package shall not
be considered part of this Package.
8. The name of the Copyright Holder may not be used to endorse or promote
products derived from this software without specific prior written permission.
9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
The End
Build.PL
Changes
LICENSE
MANIFEST.SKIP
META.json
README.md
cpanfile
examples/chat/README
examples/chat/chat-redis.psgi
examples/chat/chat-rooms.psgi
examples/chat/chat.psgi
examples/chat/public/WebSocketMain.swf
examples/chat/public/WebSocketMainInsecure.swf
examples/chat/public/chat.html
examples/chat/public/socket.io.js
examples/chat/public/stylesheets/style.css
examples/flash-policy-server
lib/PocketIO.pm
lib/PocketIO/Broadcast.pm
lib/PocketIO/Connection.pm
lib/PocketIO/Exception.pm
lib/PocketIO/Handle.pm
lib/PocketIO/Message.pm
lib/PocketIO/Pool.pm
lib/PocketIO/Pool/Redis.pm
lib/PocketIO/Resource.pm
lib/PocketIO/Room.pm
lib/PocketIO/Socket.pm
lib/PocketIO/Sockets.pm
lib/PocketIO/Test.pm
lib/PocketIO/Transport/Base.pm
lib/PocketIO/Transport/BasePolling.pm
lib/PocketIO/Transport/Htmlfile.pm
lib/PocketIO/Transport/JSONPPolling.pm
lib/PocketIO/Transport/WebSocket.pm
lib/PocketIO/Transport/XHRMultipart.pm
lib/PocketIO/Transport/XHRPolling.pm
lib/PocketIO/Util.pm
minil.toml
t/app.t
t/conn/broadcast.t
t/conn/close-timeout.t
t/conn/connect-timeout.t
t/conn/parsing.t
t/conn/reconnect-timeout.t
t/conn/socket.t
t/conn/sockets.t
t/lib/Handler.pm
t/pool.t
t/resource.t
t/room.t
t/transport/htmlfile.t
t/transport/jsonp-polling.t
t/transport/websocket.t
t/transport/xhr-polling.t
xt/changes.t
xt/pod-coverage.t
xt/pod.t
META.yml
MANIFEST
MANIFEST.SKIP view on Meta::CPAN
^blib
^pm_to_blib
.*\.old$
^Makefile$
^\.git
.tar.gz$
.swp$
.un~$
MANIFEST.bak
README.pod
Debian_CPANTS.txt
{
"abstract" : "Socket.IO PSGI application",
"author" : [
"Viacheslav Tykhanovskyi, C<vti@cpan.org>."
],
"dynamic_config" : 0,
"generated_by" : "Minilla/v0.7.5",
"license" : [
"unknown"
],
"meta-spec" : {
"url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec",
"version" : "2"
},
"name" : "PocketIO",
"no_index" : {
"directory" : [
"t",
"xt",
"inc",
"share",
"eg",
"examples",
"author",
"builder"
]
},
"prereqs" : {
"configure" : {
"requires" : {
"CPAN::Meta" : "0",
"CPAN::Meta::Prereqs" : "0",
"Module::Build" : "0.38"
}
},
"develop" : {
"requires" : {
"Test::CPAN::Meta" : "0",
"Test::MinimumVersion" : "0.10108",
"Test::Pod" : "1.41",
"Test::Spellunker" : "v0.2.7"
}
},
"runtime" : {
"requires" : {
"AnyEvent" : "0",
"Carp" : "0",
"JSON" : "2.53",
"Protocol::SocketIO" : "0.04",
"Protocol::WebSocket" : "0.009006",
"Scalar::Util" : "0",
"Test::More" : "0",
"Test::TCP" : "0"
}
}
},
"provides" : {
"PocketIO" : {
"file" : "lib/PocketIO.pm",
"version" : "0.17"
},
"PocketIO::Broadcast" : {
"file" : "lib/PocketIO/Broadcast.pm"
},
"PocketIO::Connection" : {
"file" : "lib/PocketIO/Connection.pm"
},
"PocketIO::Exception" : {
"file" : "lib/PocketIO/Exception.pm"
},
"PocketIO::Handle" : {
"file" : "lib/PocketIO/Handle.pm"
},
"PocketIO::Message" : {
"file" : "lib/PocketIO/Message.pm"
},
"PocketIO::Pool" : {
"file" : "lib/PocketIO/Pool.pm"
},
"PocketIO::Pool::Redis" : {
"file" : "lib/PocketIO/Pool/Redis.pm"
},
"PocketIO::Resource" : {
"file" : "lib/PocketIO/Resource.pm"
},
"PocketIO::Room" : {
"file" : "lib/PocketIO/Room.pm"
},
"PocketIO::Socket" : {
"file" : "lib/PocketIO/Socket.pm"
},
"PocketIO::Sockets" : {
"file" : "lib/PocketIO/Sockets.pm"
},
"PocketIO::Test" : {
"file" : "lib/PocketIO/Test.pm"
},
"PocketIO::Transport::Base" : {
"file" : "lib/PocketIO/Transport/Base.pm"
},
"PocketIO::Transport::BasePolling" : {
"file" : "lib/PocketIO/Transport/BasePolling.pm"
},
"PocketIO::Transport::Htmlfile" : {
"file" : "lib/PocketIO/Transport/Htmlfile.pm"
},
"PocketIO::Transport::JSONPPolling" : {
"file" : "lib/PocketIO/Transport/JSONPPolling.pm"
},
"PocketIO::Transport::WebSocket" : {
"file" : "lib/PocketIO/Transport/WebSocket.pm"
},
"PocketIO::Transport::XHRMultipart" : {
"file" : "lib/PocketIO/Transport/XHRMultipart.pm"
},
"PocketIO::Transport::XHRPolling" : {
"file" : "lib/PocketIO/Transport/XHRPolling.pm"
},
"PocketIO::Util" : {
"file" : "lib/PocketIO/Util.pm"
}
},
"release_status" : "stable",
"resources" : {
"bugtracker" : {
"web" : "https://github.com/vti/pocketio/issues"
},
"homepage" : "https://github.com/vti/pocketio",
"repository" : {
"url" : "git://github.com/vti/pocketio.git",
"web" : "https://github.com/vti/pocketio"
}
},
"version" : "0.17",
"x_contributors" : [
"Jens Gassmann <jens.gassmann@atomix.de>",
"Audrey Tang <audrey.tang@socialtext.com>",
"Uwe Voelker <uwe.voelker@xing.com>",
"Oskari Okko Ojala <okko@frantic.com>",
"Jason May <jason.a.may@gmail.com>",
"Michael FiG <git@michael.fig.org>",
"Peter Stuifzand <peter@stuifzand.eu>",
"tokubass <tomi21110@gmail.com>",
"Mark Grimes <mgrimes@cpan.org>",
"vti <viacheslav.t@gmail.com>"
]
}
---
abstract: 'Socket.IO PSGI application'
author:
- 'Viacheslav Tykhanovskyi, C<vti@cpan.org>.'
build_requires: {}
configure_requires:
CPAN::Meta: 0
CPAN::Meta::Prereqs: 0
Module::Build: 0.38
dynamic_config: 0
generated_by: 'Minilla/v0.7.5, CPAN::Meta::Converter version 2.130880'
license: unknown
meta-spec:
url: http://module-build.sourceforge.net/META-spec-v1.4.html
version: 1.4
name: PocketIO
no_index:
directory:
- t
- xt
- inc
- share
- eg
- examples
- author
- builder
provides:
PocketIO:
file: lib/PocketIO.pm
version: 0.17
PocketIO::Broadcast:
file: lib/PocketIO/Broadcast.pm
PocketIO::Connection:
file: lib/PocketIO/Connection.pm
PocketIO::Exception:
file: lib/PocketIO/Exception.pm
PocketIO::Handle:
file: lib/PocketIO/Handle.pm
PocketIO::Message:
file: lib/PocketIO/Message.pm
PocketIO::Pool:
file: lib/PocketIO/Pool.pm
PocketIO::Pool::Redis:
file: lib/PocketIO/Pool/Redis.pm
PocketIO::Resource:
file: lib/PocketIO/Resource.pm
PocketIO::Room:
file: lib/PocketIO/Room.pm
PocketIO::Socket:
file: lib/PocketIO/Socket.pm
PocketIO::Sockets:
file: lib/PocketIO/Sockets.pm
PocketIO::Test:
file: lib/PocketIO/Test.pm
PocketIO::Transport::Base:
file: lib/PocketIO/Transport/Base.pm
PocketIO::Transport::BasePolling:
file: lib/PocketIO/Transport/BasePolling.pm
PocketIO::Transport::Htmlfile:
file: lib/PocketIO/Transport/Htmlfile.pm
PocketIO::Transport::JSONPPolling:
file: lib/PocketIO/Transport/JSONPPolling.pm
PocketIO::Transport::WebSocket:
file: lib/PocketIO/Transport/WebSocket.pm
PocketIO::Transport::XHRMultipart:
file: lib/PocketIO/Transport/XHRMultipart.pm
PocketIO::Transport::XHRPolling:
file: lib/PocketIO/Transport/XHRPolling.pm
PocketIO::Util:
file: lib/PocketIO/Util.pm
requires:
AnyEvent: 0
Carp: 0
JSON: 2.53
Protocol::SocketIO: 0.04
Protocol::WebSocket: 0.009006
Scalar::Util: 0
Test::More: 0
Test::TCP: 0
resources:
bugtracker: https://github.com/vti/pocketio/issues
homepage: https://github.com/vti/pocketio
repository: git://github.com/vti/pocketio.git
version: 0.17
x_contributors:
- 'Jens Gassmann <jens.gassmann@atomix.de>'
- 'Audrey Tang <audrey.tang@socialtext.com>'
- 'Uwe Voelker <uwe.voelker@xing.com>'
- 'Oskari Okko Ojala <okko@frantic.com>'
- 'Jason May <jason.a.may@gmail.com>'
- 'Michael FiG <git@michael.fig.org>'
- 'Peter Stuifzand <peter@stuifzand.eu>'
- 'tokubass <tomi21110@gmail.com>'
- 'Mark Grimes <mgrimes@cpan.org>'
- 'vti <viacheslav.t@gmail.com>'
# NAME
PocketIO - Socket.IO PSGI application
# SYNOPSIS
use Plack::Builder;
builder {
mount '/socket.io' => PocketIO->new(
handler => sub {
my $self = shift;
$self->on(
'message' => sub {
my $self = shift;
my ($message) = @_;
...;
}
);
$self->send({buffer => []});
}
);
$app;
};
# or
builder {
mount '/socket.io' =>
PocketIO->new(class => 'MyApp::Handler', method => 'run');
$app;
};
# DESCRIPTION
[PocketIO](http://search.cpan.org/perldoc?PocketIO) is a server implementation of SocketIO in Perl, you still need
`socket.io` javascript library on the client.
[PocketIO](http://search.cpan.org/perldoc?PocketIO) aims to have API as close as possible to the Node.js implementation
and sometimes it might look not very perlish.
## How to use
First you mount [PocketIO](http://search.cpan.org/perldoc?PocketIO) as a normal [Plack](http://search.cpan.org/perldoc?Plack) application. It is recommended
to mount it to the `/socket.io` path since that will not require any changes on
the client side.
When the client is connected your handler is called with a [PocketIO::Socket](http://search.cpan.org/perldoc?PocketIO::Socket)
object as a first parameter.
## Sending and receiving messages
A simple echo handler can look like this:
sub {
my $self = shift;
$self->on('message' => sub {
my $self = shift;
my ($message) = @_;
$self->send($message);
});
}
## Sending and receiving events
Events are special messages that behave like rpc calls.
sub {
my $self = shift;
$self->on('username' => sub {
my $self = shift;
my ($nick) = @_;
...
});
$self->emit('username', 'vti');
}
## Broadcasting and sending messages/events to everybody
Broadcasting is sending messages to everybody except you:
$self->broadcast->send('foo');
$self->broadcast->emit('foo');
Method `sockets` represents all connected clients:
$self->sockets->send('foo');
$self->sockets->emit('foo');
## Acknowlegements
Sometimes you want to know when the client received a message or event. In order
to achieve this just pass a callback as the last parameter:
$self->send('foo', sub {'client got message'});
$self->emit('foo', sub {'client got event'});
## Storing data in the socket object
Often it is required to store some data in the client object. Instead of using
global variables there are two handy methods:
sub {
my $self = shift;
$self->set(foo => 'bar', sub { 'ready' });
$self->get('foo' => sub {
my $self = shift;
my ($err, $foo) = @_;
});
}
## Namespacing
Not implemented yet.
## Volatile messages
Not implemented yet.
## Rooms
A room is a named group of connections for more fine-grained
broadcasts. You can subscribe or unsubscribe a socket to/from a room:
sub {
my $self = shift;
$self->join('a room');
$self->sockets->in('a room')->emit('message', data);
$self->broadcast->to('a room')->emit("other message");
}
# CONFIGURATIONS
- handler
PocketIO->new(
handler => sub {
my $socket = shift;
$socket->on(
'message' => sub {
my $socket = shift;
}
);
$socket->send('hello');
}
);
- class or instance, method
PocketIO->new(class => 'MyHandler', method => 'run');
# or
PocketIO->new(instance => MyHandler->new(foo => 'bar'), method => 'run');
package MyHandler;
sub new { ... } # or use Moose, Boose, Goose, Doose
sub run {
my $self = shift;
return sub {
# same code as above
}
}
Loads `class`, creates a new object or uses a passed `instance` and runs
`run` method expecting it to return an anonymous subroutine.
# TLS/SSL
For TLS/SSL a secure proxy is needed. `stunnel` or [App::TLSMe](http://search.cpan.org/perldoc?App::TLSMe) are
recommended.
# SCALING
See [PocketIO::Pool::Redis](http://search.cpan.org/perldoc?PocketIO::Pool::Redis).
# DEBUGGING
Use `POCKETIO_DEBUG` and `POCKETIO_CONNECTION_DEBUG` variables for debugging.
# METHODS
## `new`
Create a new [PocketIO](http://search.cpan.org/perldoc?PocketIO) instance.
## `pool`
Holds [PocketIO::Pool](http://search.cpan.org/perldoc?PocketIO::Pool) object by default.
## `call`
For Plack apps compatibility.
## `to_app`
Returns PSGI code reference.
# SEE ALSO
More information about SocketIO you can find on the website [http://socket.io/](http://socket.io/), or
on the GitHub [https://github.com/LearnBoost/Socket.IO](https://github.com/LearnBoost/Socket.IO).
[Protocol::SocketIO](http://search.cpan.org/perldoc?Protocol::SocketIO), [PSGI](http://search.cpan.org/perldoc?PSGI)
# DEVELOPMENT
## Repository
http://github.com/vti/pocketio
# CREDITS
Socket.IO author(s) and contributors.
Jens Gassmann
Uwe Voelker
Oskari Okko Ojala
Jason May
Michael FiG
Peter Stuifzand
tokubass
mvgrimes
# AUTHOR
Viacheslav Tykhanovskyi, `vti@cpan.org`.
# COPYRIGHT AND LICENSE
Copyright (C) 2011-2013, Viacheslav Tykhanovskyi
This program is free software, you can redistribute it and/or modify it under
the terms of the Artistic License version 2.0.
requires 'Carp' => '0';
requires 'Scalar::Util' => '0';
requires 'AnyEvent' => '0';
requires 'JSON' => '2.53';
requires 'Protocol::SocketIO' => '0.04';
requires 'Protocol::WebSocket' => '0.009006';
requires 'Test::More' => '0';
requires 'Test::TCP' => '0';
examples/chat/README view on Meta::CPAN
This is an example from Socket.IO-node distribution adapted for PocketIO.
examples/chat/chat-redis.psgi view on Meta::CPAN
my $root;
BEGIN {
use File::Basename ();
use File::Spec ();
$root = File::Basename::dirname(__FILE__);
$root = File::Spec->rel2abs($root);
unshift @INC, "$root/../../lib";
}
use PocketIO;
use PocketIO::Pool::Redis;
use JSON;
use Plack::App::File;
use Plack::Builder;
use Plack::Middleware::Static;
my $nicknames = {};
builder {
mount '/socket.io/socket.io.js' =>
Plack::App::File->new(file => "$root/public/socket.io.js");
mount '/socket.io/static/flashsocket/WebSocketMain.swf' =>
Plack::App::File->new(file => "$root/public/WebSocketMain.swf");
mount '/socket.io/static/flashsocket/WebSocketMainInsecure.swf' =>
Plack::App::File->new(file => "$root/public/WebSocketMainInsecure.swf");
mount '/socket.io' => PocketIO->new(
pool => PocketIO::Pool::Redis->new,
handler => sub {
my $self = shift;
$self->on(
'user message' => sub {
my $self = shift;
my ($message) = @_;
$self->get(
'nick' => sub {
my ($self, $err, $nick) = @_;
$self->broadcast->emit('user message', $nick,
$message);
}
);
}
);
$self->on(
'nickname' => sub {
my $self = shift;
my ($nick, $cb) = @_;
if ($nicknames->{$nick}) {
$cb->(JSON::true);
}
else {
$cb->(JSON::false);
$self->set(nick => $nick);
$nicknames->{$nick} = $nick;
$self->broadcast->emit('announcement',
$nick . ' connected');
$self->sockets->emit('nicknames', $nicknames);
}
}
);
$self->on(
'disconnect' => sub {
my $self = shift;
$self->get(
'nick' => sub {
my ($self, $err, $nick) = @_;
delete $nicknames->{$nick};
$self->broadcast->emit('announcement',
$nick . ' disconnected');
$self->broadcast->emit('nicknames', $nicknames);
}
);
}
);
}
);
mount '/' => builder {
enable "Static",
path => qr/\.(?:js|css|jpe?g|gif|png|html?|swf|ico)$/,
root => "$root/public";
enable "SimpleLogger", level => 'debug';
my $html = do {
local $/;
open my $fh, '<', "$root/public/chat.html"
or die $!;
<$fh>;
};
sub {
[ 200,
[ 'Content-Type' => 'text/html',
'Content-Length' => length($html)
],
[$html]
];
};
};
};
examples/chat/chat-rooms.psgi view on Meta::CPAN
my $root;
BEGIN {
use File::Basename ();
use File::Spec ();
$root = File::Basename::dirname(__FILE__);
$root = File::Spec->rel2abs($root);
unshift @INC, "$root/../../lib";
}
use PocketIO;
use JSON;
use Plack::App::File;
use Plack::Builder;
use Plack::Middleware::Static;
my $nicknames = {};
builder {
mount '/socket.io/socket.io.js' =>
Plack::App::File->new(file => "$root/public/socket.io.js");
mount '/socket.io/static/flashsocket/WebSocketMain.swf' =>
Plack::App::File->new(file => "$root/public/WebSocketMain.swf");
mount '/socket.io/static/flashsocket/WebSocketMainInsecure.swf' =>
Plack::App::File->new(file => "$root/public/WebSocketMainInsecure.swf");
mount '/socket.io' => PocketIO->new(
handler => sub {
my $self = shift;
$self->on(
'user message' => sub {
my $self = shift;
my ($message) = @_;
$self->get('nick' => sub {
my ($self, $err, $nick) = @_;
if ($message =~ m{/join\s*(.*)}) {
$self->join($1);
$self->sockets->in($1)->emit('user message', $nick, 'Joined room');
}
elsif ($message =~ m{/leave \s*(.*)}) {
$self->leave($1);
$self->sockets->in($1)->emit('user message', $nick, 'Left room');
}
elsif ($message =~ m{/room\s*([^ ]+)\s*(.*)}) {
$self->sockets->in($1)->emit('user message', $nick, "[$1]: $2");
}
else {
$self->broadcast->emit('user message', $nick, $message);
}
});
}
);
$self->on(
'nickname' => sub {
my $self = shift;
my ($nick, $cb) = @_;
if ($nicknames->{$nick}) {
$cb->(JSON::true);
}
else {
$cb->(JSON::false);
$self->set(nick => $nick);
$nicknames->{$nick} = $nick;
$self->broadcast->emit('announcement', $nick . ' connected');
$self->sockets->emit('nicknames', $nicknames);
}
}
);
$self->on(
'disconnect' => sub {
my $self = shift;
$self->get(
'nick' => sub {
my ($self, $err, $nick) = @_;
delete $nicknames->{$nick};
$self->broadcast->emit('announcement',
$nick . ' disconnected');
$self->broadcast->emit('nicknames', $nicknames);
}
);
}
);
}
);
mount '/' => builder {
enable "Static",
path => qr/\.(?:js|css|jpe?g|gif|png|html?|swf|ico)$/,
root => "$root/public";
enable "SimpleLogger", level => 'debug';
my $html = do {
local $/;
open my $fh, '<', "$root/public/chat.html"
or die $!;
<$fh>;
};
sub {
[ 200,
[ 'Content-Type' => 'text/html',
'Content-Length' => length($html)
],
[$html]
];
};
};
};
examples/chat/chat.psgi view on Meta::CPAN
my $root;
BEGIN {
use File::Basename ();
use File::Spec ();
$root = File::Basename::dirname(__FILE__);
$root = File::Spec->rel2abs($root);
unshift @INC, "$root/../../lib";
}
use PocketIO;
use JSON;
use Plack::App::File;
use Plack::Builder;
use Plack::Middleware::Static;
my $nicknames = {};
builder {
mount '/socket.io/socket.io.js' =>
Plack::App::File->new(file => "$root/public/socket.io.js");
mount '/socket.io/static/flashsocket/WebSocketMain.swf' =>
Plack::App::File->new(file => "$root/public/WebSocketMain.swf");
mount '/socket.io/static/flashsocket/WebSocketMainInsecure.swf' =>
Plack::App::File->new(file => "$root/public/WebSocketMainInsecure.swf");
mount '/socket.io' => PocketIO->new(
handler => sub {
my $self = shift;
$self->on(
'user message' => sub {
my $self = shift;
my ($message) = @_;
$self->get('nick' => sub {
my ($self, $err, $nick) = @_;
$self->broadcast->emit('user message', $nick, $message);
});
}
);
$self->on(
'nickname' => sub {
my $self = shift;
my ($nick, $cb) = @_;
if ($nicknames->{$nick}) {
$cb->(JSON::true);
}
else {
$cb->(JSON::false);
$self->set(nick => $nick);
$nicknames->{$nick} = $nick;
$self->broadcast->emit('announcement', $nick . ' connected');
$self->sockets->emit('nicknames', $nicknames);
}
}
);
$self->on(
'disconnect' => sub {
my $self = shift;
$self->get(
'nick' => sub {
my ($self, $err, $nick) = @_;
delete $nicknames->{$nick};
$self->broadcast->emit('announcement',
$nick . ' disconnected');
$self->broadcast->emit('nicknames', $nicknames);
}
);
}
);
}
);
mount '/' => builder {
enable "Static",
path => qr/\.(?:js|css|jpe?g|gif|png|html?|swf|ico)$/,
root => "$root/public";
enable "SimpleLogger", level => 'debug';
my $html = do {
local $/;
open my $fh, '<', "$root/public/chat.html"
or die $!;
<$fh>;
};
sub {
[ 200,
[ 'Content-Type' => 'text/html',
'Content-Length' => length($html)
],
[$html]
];
};
};
};
examples/chat/public/chat.html view on Meta::CPAN
<!DOCTYPE html><html><head><link href="/stylesheets/style.css" rel="stylesheet"><script src="http://code.jquery.com/jquery-1.6.1.min.js"></script><script src="/socket.io/socket.io.js"></script><script>// socket.io specific code
var socket = io.connect();
socket.on('connect', function () {
$('#chat').addClass('connected');
});
socket.on('announcement', function (msg) {
$('#lines').append($('<p>').append($('<em>').text(msg)));
});
socket.on('nicknames', function (nicknames) {
$('#nicknames').empty().append($('<span>Online: </span>'));
for (var i in nicknames) {
$('#nicknames').append($('<b>').text(nicknames[i]));
}
});
socket.on('user message', message);
socket.on('reconnect', function () {
$('#lines').remove();
message('System', 'Reconnected to the server');
});
socket.on('reconnecting', function () {
message('System', 'Attempting to re-connect to the server');
});
socket.on('error', function (e) {
message('System', e ? e : 'A unknown error occurred');
});
function message (from, msg) {
$('#lines').append($('<p>').append($('<b>').text(from), msg));
}
// dom manipulation
$(function () {
$('#set-nickname').submit(function (ev) {
socket.emit('nickname', $('#nick').val(), function (set) {
if (!set) {
clear();
return $('#chat').addClass('nickname-set');
}
$('#nickname-err').css('visibility', 'visible');
});
return false;
});
$('#send-message').submit(function () {
message('me', $('#message').val());
socket.emit('user message', $('#message').val());
clear();
$('#lines').get(0).scrollTop = 10000000;
return false;
});
function clear () {
$('#message').val('').focus();
};
});
</script></head><body><div id="chat"><div id="nickname"><form id="set-nickname" class="wrap"><p>Please type in your nickname and press enter.</p><input id="nick"><p id="nickname-err">Nickname already in use</p></form></div><div id="connecting"><div c...
examples/chat/public/socket.io.js view on Meta::CPAN
/*! Socket.IO.js build:0.8.5, development. Copyright(c) 2011 LearnBoost <dev@learnboost.com> MIT Licensed */
/**
* socket.io
* Copyright(c) 2011 LearnBoost <dev@learnboost.com>
* MIT Licensed
*/
(function (exports) {
/**
* IO namespace.
*
* @namespace
*/
var io = exports;
/**
* Socket.IO version
*
* @api public
*/
io.version = '0.8.5';
/**
* Protocol implemented.
*
* @api public
*/
io.protocol = 1;
/**
* Available transports, these will be populated with the available transports
*
* @api public
*/
io.transports = [];
/**
* Keep track of jsonp callbacks.
*
* @api private
*/
io.j = [];
/**
* Keep track of our io.Sockets
*
* @api private
*/
io.sockets = {};
/**
* Manages connections to hosts.
*
* @param {String} uri
* @Param {Boolean} force creation of new socket (defaults to false)
* @api public
*/
io.connect = function (host, details) {
var uri = io.util.parseUri(host)
, uuri
, socket;
if ('undefined' != typeof document) {
uri.protocol = uri.protocol || document.location.protocol.slice(0, -1);
uri.host = uri.host || document.domain;
uri.port = uri.port || document.location.port;
}
uuri = io.util.uniqueUri(uri);
var options = {
host: uri.host
, secure: 'https' == uri.protocol
, port: uri.port || ('https' == uri.protocol ? 443 : 80)
, query: uri.query || ''
};
io.util.merge(options, details);
if (options['force new connection'] || !io.sockets[uuri]) {
socket = new io.Socket(options);
}
if (!options['force new connection'] && socket) {
io.sockets[uuri] = socket;
}
socket = socket || io.sockets[uuri];
// if path is different from '' or /
return socket.of(uri.path.length > 1 ? uri.path : '');
};
})('object' === typeof module ? module.exports : (window.io = {}));
/**
* socket.io
* Copyright(c) 2011 LearnBoost <dev@learnboost.com>
* MIT Licensed
*/
(function (exports, global) {
/**
* Utilities namespace.
*
* @namespace
*/
var util = exports.util = {};
/**
* Parses an URI
*
* @author Steven Levithan <stevenlevithan.com> (MIT license)
* @api public
*/
var re = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
var parts = ['source', 'protocol', 'authority', 'userInfo', 'user', 'password',
'host', 'port', 'relative', 'path', 'directory', 'file', 'query',
'anchor'];
util.parseUri = function (str) {
var m = re.exec(str || '')
, uri = {}
, i = 14;
while (i--) {
uri[parts[i]] = m[i] || '';
}
return uri;
};
/**
* Produces a unique url that identifies a Socket.IO connection.
*
* @param {Object} uri
* @api public
*/
util.uniqueUri = function (uri) {
var protocol = uri.protocol
, host = uri.host
, port = uri.port;
if ('document' in global) {
host = host || document.domain;
port = port || (protocol == 'https'
&& document.location.protocol !== 'https:' ? 443 : document.location.port);
} else {
host = host || 'localhost';
if (!port && protocol == 'https') {
port = 443;
}
}
return (protocol || 'http') + '://' + host + ':' + (port || 80);
};
/**
* Mergest 2 query strings in to once unique query string
*
* @param {String} base
* @param {String} addition
* @api public
*/
util.query = function (base, addition) {
var query = util.chunkQuery(base || '')
, components = [];
util.merge(query, util.chunkQuery(addition || ''));
for (var part in query) {
if (query.hasOwnProperty(part)) {
components.push(part + '=' + query[part]);
}
}
return components.length ? '?' + components.join('&') : '';
};
/**
* Transforms a querystring in to an object
*
* @param {String} qs
* @api public
*/
util.chunkQuery = function (qs) {
var query = {}
, params = qs.split('&')
, i = 0
, l = params.length
, kv;
for (; i < l; ++i) {
kv = params[i].split('=');
if (kv[0]) {
query[kv[0]] = decodeURIComponent(kv[1]);
}
}
return query;
};
/**
* Executes the given function when the page is loaded.
*
* io.util.load(function () { console.log('page loaded'); });
*
* @param {Function} fn
* @api public
*/
var pageLoaded = false;
util.load = function (fn) {
if ('document' in global && document.readyState === 'complete' || pageLoaded) {
return fn();
}
util.on(global, 'load', fn, false);
};
/**
* Adds an event.
*
* @api private
*/
util.on = function (element, event, fn, capture) {
if (element.attachEvent) {
element.attachEvent('on' + event, fn);
} else if (element.addEventListener) {
element.addEventListener(event, fn, capture);
}
};
/**
* Generates the correct `XMLHttpRequest` for regular and cross domain requests.
*
* @param {Boolean} [xdomain] Create a request that can be used cross domain.
* @returns {XMLHttpRequest|false} If we can create a XMLHttpRequest.
* @api private
*/
util.request = function (xdomain) {
if ('undefined' != typeof window) {
if (xdomain && window.XDomainRequest) {
return new XDomainRequest();
}
if (window.XMLHttpRequest && (!xdomain || util.ua.hasCORS)) {
return new XMLHttpRequest();
}
if (!xdomain) {
try {
return new window.ActiveXObject('Microsoft.XMLHTTP');
} catch(e) { }
}
}
return null;
};
/**
* XHR based transport constructor.
*
* @constructor
* @api public
*/
/**
* Change the internal pageLoaded value.
*/
if ('undefined' != typeof window) {
util.load(function () {
pageLoaded = true;
});
}
/**
* Defers a function to ensure a spinner is not displayed by the browser
*
* @param {Function} fn
* @api public
*/
util.defer = function (fn) {
if (!util.ua.webkit) {
return fn();
}
util.load(function () {
setTimeout(fn, 100);
});
};
/**
* Merges two objects.
*
* @api public
*/
util.merge = function merge (target, additional, deep, lastseen) {
var seen = lastseen || []
, depth = typeof deep == 'undefined' ? 2 : deep
, prop;
for (prop in additional) {
if (additional.hasOwnProperty(prop) && util.indexOf(seen, prop) < 0) {
if (typeof target[prop] !== 'object' || !depth) {
target[prop] = additional[prop];
seen.push(additional[prop]);
} else {
util.merge(target[prop], additional[prop], depth - 1, seen);
}
}
}
return target;
};
/**
* Merges prototypes from objects
*
* @api public
*/
util.mixin = function (ctor, ctor2) {
util.merge(ctor.prototype, ctor2.prototype);
};
/**
* Shortcut for prototypical and static inheritance.
*
* @api private
*/
util.inherit = function (ctor, ctor2) {
function f() {};
f.prototype = ctor2.prototype;
ctor.prototype = new f;
};
/**
* Checks if the given object is an Array.
*
* io.util.isArray([]); // true
* io.util.isArray({}); // false
*
* @param Object obj
* @api public
*/
util.isArray = Array.isArray || function (obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
};
/**
* Intersects values of two arrays into a third
*
* @api public
*/
util.intersect = function (arr, arr2) {
var ret = []
, longest = arr.length > arr2.length ? arr : arr2
, shortest = arr.length > arr2.length ? arr2 : arr;
for (var i = 0, l = shortest.length; i < l; i++) {
if (~util.indexOf(longest, shortest[i]))
ret.push(shortest[i]);
}
return ret;
}
/**
* Array indexOf compatibility.
*
* @see bit.ly/a5Dxa2
* @api public
*/
util.indexOf = function (arr, o, i) {
if (Array.prototype.indexOf) {
return Array.prototype.indexOf.call(arr, o, i);
}
for (var j = arr.length, i = i < 0 ? i + j < 0 ? 0 : i + j : i || 0;
i < j && arr[i] !== o; i++);
return j <= i ? -1 : i;
};
/**
* Converts enumerables to array.
*
* @api public
*/
util.toArray = function (enu) {
var arr = [];
for (var i = 0, l = enu.length; i < l; i++)
arr.push(enu[i]);
return arr;
};
/**
* UA / engines detection namespace.
*
* @namespace
*/
util.ua = {};
/**
* Whether the UA supports CORS for XHR.
*
* @api public
*/
util.ua.hasCORS = 'undefined' != typeof window && window.XMLHttpRequest &&
(function () {
try {
var a = new XMLHttpRequest();
} catch (e) {
return false;
}
return a.withCredentials != undefined;
})();
/**
* Detect webkit.
*
* @api public
*/
util.ua.webkit = 'undefined' != typeof navigator
&& /webkit/i.test(navigator.userAgent);
})(
'undefined' != typeof window ? io : module.exports
, this
);
/**
* socket.io
* Copyright(c) 2011 LearnBoost <dev@learnboost.com>
* MIT Licensed
*/
(function (exports, io) {
/**
* Expose constructor.
*/
exports.EventEmitter = EventEmitter;
/**
* Event emitter constructor.
*
* @api public.
*/
function EventEmitter () {};
/**
* Adds a listener
*
* @api public
*/
EventEmitter.prototype.on = function (name, fn) {
if (!this.$events) {
this.$events = {};
}
if (!this.$events[name]) {
this.$events[name] = fn;
} else if (io.util.isArray(this.$events[name])) {
this.$events[name].push(fn);
} else {
this.$events[name] = [this.$events[name], fn];
}
return this;
};
EventEmitter.prototype.addListener = EventEmitter.prototype.on;
/**
* Adds a volatile listener.
*
* @api public
*/
EventEmitter.prototype.once = function (name, fn) {
var self = this;
function on () {
self.removeListener(name, on);
fn.apply(this, arguments);
};
on.listener = fn;
this.on(name, on);
return this;
};
/**
* Removes a listener.
*
* @api public
*/
EventEmitter.prototype.removeListener = function (name, fn) {
if (this.$events && this.$events[name]) {
var list = this.$events[name];
if (io.util.isArray(list)) {
var pos = -1;
for (var i = 0, l = list.length; i < l; i++) {
if (list[i] === fn || (list[i].listener && list[i].listener === fn)) {
pos = i;
break;
}
}
if (pos < 0) {
return this;
}
list.splice(pos, 1);
if (!list.length) {
delete this.$events[name];
}
} else if (list === fn || (list.listener && list.listener === fn)) {
delete this.$events[name];
}
}
return this;
};
/**
* Removes all listeners for an event.
*
* @api public
*/
EventEmitter.prototype.removeAllListeners = function (name) {
// TODO: enable this when node 0.5 is stable
//if (name === undefined) {
//this.$events = {};
//return this;
//}
if (this.$events && this.$events[name]) {
this.$events[name] = null;
}
return this;
};
/**
* Gets all listeners for a certain event.
*
* @api publci
*/
EventEmitter.prototype.listeners = function (name) {
if (!this.$events) {
this.$events = {};
}
if (!this.$events[name]) {
this.$events[name] = [];
}
if (!io.util.isArray(this.$events[name])) {
this.$events[name] = [this.$events[name]];
}
return this.$events[name];
};
/**
* Emits an event.
*
* @api public
*/
EventEmitter.prototype.emit = function (name) {
if (!this.$events) {
return false;
}
var handler = this.$events[name];
if (!handler) {
return false;
}
var args = Array.prototype.slice.call(arguments, 1);
if ('function' == typeof handler) {
handler.apply(this, args);
} else if (io.util.isArray(handler)) {
var listeners = handler.slice();
for (var i = 0, l = listeners.length; i < l; i++) {
listeners[i].apply(this, args);
}
} else {
return false;
}
return true;
};
})(
'undefined' != typeof io ? io : module.exports
, 'undefined' != typeof io ? io : module.parent.exports
);
/**
* socket.io
* Copyright(c) 2011 LearnBoost <dev@learnboost.com>
* MIT Licensed
*/
/**
* Based on JSON2 (http://www.JSON.org/js.html).
*/
(function (exports, nativeJSON) {
"use strict";
// use native JSON if it's available
if (nativeJSON && nativeJSON.parse){
return exports.JSON = {
parse: nativeJSON.parse
, stringify: nativeJSON.stringify
}
}
var JSON = exports.JSON = {};
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
function date(d, key) {
return isFinite(d.valueOf()) ?
d.getUTCFullYear() + '-' +
f(d.getUTCMonth() + 1) + '-' +
f(d.getUTCDate()) + 'T' +
f(d.getUTCHours()) + ':' +
f(d.getUTCMinutes()) + ':' +
f(d.getUTCSeconds()) + 'Z' : null;
};
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
gap,
indent,
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
},
rep;
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string' ? c :
'\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' : '"' + string + '"';
}
function str(key, holder) {
// Produce a string from holder[key].
var i, // The loop counter.
k, // The member key.
v, // The member value.
length,
mind = gap,
partial,
value = holder[key];
// If the value has a toJSON method, call it to obtain a replacement value.
if (value instanceof Date) {
value = date(key);
}
// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.
if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
// What happens next depends on the value's type.
switch (typeof value) {
case 'string':
return quote(value);
case 'number':
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(value) ? String(value) : 'null';
case 'boolean':
case 'null':
// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.
return String(value);
// If the type is 'object', we might be dealing with an object or an array or
// null.
case 'object':
// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.
if (!value) {
return 'null';
}
// Make an array to hold the partial results of stringifying this object value.
gap += indent;
partial = [];
// Is the value an array?
if (Object.prototype.toString.apply(value) === '[object Array]') {
// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
// Join all of the elements together, separated with commas, and wrap them in
// brackets.
v = partial.length === 0 ? '[]' : gap ?
'[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' :
'[' + partial.join(',') + ']';
gap = mind;
return v;
}
// If the replacer is an array, use it to select the members to be stringified.
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
if (typeof rep[i] === 'string') {
k = rep[i];
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
} else {
// Otherwise, iterate through all of the keys in the object.
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
v = partial.length === 0 ? '{}' : gap ?
'{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' :
'{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
// If the JSON object does not yet have a stringify method, give it one.
JSON.stringify = function (value, replacer, space) {
// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.
var i;
gap = '';
indent = '';
// If the space parameter is a number, make an indent string containing that
// many spaces.
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
// If the space parameter is a string, it will be used as the indent string.
} else if (typeof space === 'string') {
indent = space;
}
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.
return str('', {'': value});
};
// If the JSON object does not yet have a parse method, give it one.
JSON.parse = function (text, reviver) {
// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.
var j;
function walk(holder, key) {
// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
text = String(text);
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.
return typeof reviver === 'function' ?
walk({'': j}, '') : j;
}
// If the text is not JSON parseable, then a SyntaxError is thrown.
throw new SyntaxError('JSON.parse');
};
})(
'undefined' != typeof io ? io : module.exports
, typeof JSON !== 'undefined' ? JSON : undefined
);
/**
* socket.io
* Copyright(c) 2011 LearnBoost <dev@learnboost.com>
* MIT Licensed
*/
(function (exports, io) {
/**
* Parser namespace.
*
* @namespace
*/
var parser = exports.parser = {};
/**
* Packet types.
*/
var packets = parser.packets = [
'disconnect'
, 'connect'
, 'heartbeat'
, 'message'
, 'json'
, 'event'
, 'ack'
, 'error'
, 'noop'
];
/**
* Errors reasons.
*/
var reasons = parser.reasons = [
'transport not supported'
, 'client not handshaken'
, 'unauthorized'
];
/**
* Errors advice.
*/
var advice = parser.advice = [
'reconnect'
];
/**
* Shortcuts.
*/
var JSON = io.JSON
, indexOf = io.util.indexOf;
/**
* Encodes a packet.
*
* @api private
*/
parser.encodePacket = function (packet) {
var type = indexOf(packets, packet.type)
, id = packet.id || ''
, endpoint = packet.endpoint || ''
, ack = packet.ack
, data = null;
switch (packet.type) {
case 'error':
var reason = packet.reason ? indexOf(reasons, packet.reason) : ''
, adv = packet.advice ? indexOf(advice, packet.advice) : '';
if (reason !== '' || adv !== '')
data = reason + (adv !== '' ? ('+' + adv) : '');
break;
case 'message':
if (packet.data !== '')
data = packet.data;
break;
case 'event':
var ev = { name: packet.name };
if (packet.args && packet.args.length) {
ev.args = packet.args;
}
data = JSON.stringify(ev);
break;
case 'json':
data = JSON.stringify(packet.data);
break;
case 'connect':
if (packet.qs)
data = packet.qs;
break;
case 'ack':
data = packet.ackId
+ (packet.args && packet.args.length
? '+' + JSON.stringify(packet.args) : '');
break;
}
// construct packet with required fragments
var encoded = [
type
, id + (ack == 'data' ? '+' : '')
, endpoint
];
// data fragment is optional
if (data !== null && data !== undefined)
encoded.push(data);
return encoded.join(':');
};
/**
* Encodes multiple messages (payload).
*
* @param {Array} messages
* @api private
*/
parser.encodePayload = function (packets) {
var decoded = '';
if (packets.length == 1)
return packets[0];
for (var i = 0, l = packets.length; i < l; i++) {
var packet = packets[i];
decoded += '\ufffd' + packet.length + '\ufffd' + packets[i];
}
return decoded;
};
/**
* Decodes a packet
*
* @api private
*/
var regexp = /([^:]+):([0-9]+)?(\+)?:([^:]+)?:?([\s\S]*)?/;
parser.decodePacket = function (data) {
var pieces = data.match(regexp);
if (!pieces) return {};
var id = pieces[2] || ''
, data = pieces[5] || ''
, packet = {
type: packets[pieces[1]]
, endpoint: pieces[4] || ''
};
// whether we need to acknowledge the packet
if (id) {
packet.id = id;
if (pieces[3])
packet.ack = 'data';
else
packet.ack = true;
}
// handle different packet types
switch (packet.type) {
case 'error':
var pieces = data.split('+');
packet.reason = reasons[pieces[0]] || '';
packet.advice = advice[pieces[1]] || '';
break;
case 'message':
packet.data = data || '';
break;
case 'event':
try {
var opts = JSON.parse(data);
packet.name = opts.name;
packet.args = opts.args;
} catch (e) { }
packet.args = packet.args || [];
break;
case 'json':
try {
packet.data = JSON.parse(data);
} catch (e) { }
break;
case 'connect':
packet.qs = data || '';
break;
case 'ack':
var pieces = data.match(/^([0-9]+)(\+)?(.*)/);
if (pieces) {
packet.ackId = pieces[1];
packet.args = [];
if (pieces[3]) {
try {
packet.args = pieces[3] ? JSON.parse(pieces[3]) : [];
} catch (e) { }
}
}
break;
case 'disconnect':
case 'heartbeat':
break;
};
return packet;
};
/**
* Decodes data payload. Detects multiple messages
*
* @return {Array} messages
* @api public
*/
parser.decodePayload = function (data) {
// IE doesn't like data[i] for unicode chars, charAt works fine
if (data.charAt(0) == '\ufffd') {
var ret = [];
for (var i = 1, length = ''; i < data.length; i++) {
if (data.charAt(i) == '\ufffd') {
ret.push(parser.decodePacket(data.substr(i + 1).substr(0, length)));
i += Number(length) + 1;
length = '';
} else {
length += data.charAt(i);
}
}
return ret;
} else {
return [parser.decodePacket(data)];
}
};
})(
'undefined' != typeof io ? io : module.exports
, 'undefined' != typeof io ? io : module.parent.exports
);
/**
* socket.io
* Copyright(c) 2011 LearnBoost <dev@learnboost.com>
* MIT Licensed
*/
(function (exports, io) {
/**
* Expose constructor.
*/
exports.Transport = Transport;
/**
* This is the transport template for all supported transport methods.
*
* @constructor
* @api public
*/
function Transport (socket, sessid) {
this.socket = socket;
this.sessid = sessid;
};
/**
* Apply EventEmitter mixin.
*/
io.util.mixin(Transport, io.EventEmitter);
/**
* Handles the response from the server. When a new response is received
* it will automatically update the timeout, decode the message and
* forwards the response to the onMessage function for further processing.
*
* @param {String} data Response from the server.
* @api private
*/
Transport.prototype.onData = function (data) {
this.clearCloseTimeout();
this.setCloseTimeout();
if (data !== '') {
// todo: we should only do decodePayload for xhr transports
var msgs = io.parser.decodePayload(data);
if (msgs && msgs.length) {
for (var i = 0, l = msgs.length; i < l; i++) {
this.onPacket(msgs[i]);
}
}
}
return this;
};
/**
* Handles packets.
*
* @api private
*/
Transport.prototype.onPacket = function (packet) {
if (packet.type == 'heartbeat') {
return this.onHeartbeat();
}
if (packet.type == 'connect' && packet.endpoint == '') {
this.onConnect();
}
this.socket.onPacket(packet);
return this;
};
/**
* Sets close timeout
*
* @api private
*/
Transport.prototype.setCloseTimeout = function () {
if (!this.closeTimeout) {
var self = this;
this.closeTimeout = setTimeout(function () {
self.onDisconnect();
}, this.socket.closeTimeout);
}
};
/**
* Called when transport disconnects.
*
* @api private
*/
Transport.prototype.onDisconnect = function () {
if (this.close) this.close();
this.clearTimeouts();
this.socket.onDisconnect();
return this;
};
/**
* Called when transport connects
*
* @api private
*/
Transport.prototype.onConnect = function () {
this.socket.onConnect();
return this;
}
/**
* Clears close timeout
*
* @api private
*/
Transport.prototype.clearCloseTimeout = function () {
if (this.closeTimeout) {
clearTimeout(this.closeTimeout);
this.closeTimeout = null;
}
};
/**
* Clear timeouts
*
* @api private
*/
Transport.prototype.clearTimeouts = function () {
this.clearCloseTimeout();
if (this.reopenTimeout) {
clearTimeout(this.reopenTimeout);
}
};
/**
* Sends a packet
*
* @param {Object} packet object.
* @api private
*/
Transport.prototype.packet = function (packet) {
this.send(io.parser.encodePacket(packet));
};
/**
* Send the received heartbeat message back to server. So the server
* knows we are still connected.
*
* @param {String} heartbeat Heartbeat response from the server.
* @api private
*/
Transport.prototype.onHeartbeat = function (heartbeat) {
this.packet({ type: 'heartbeat' });
};
/**
* Called when the transport opens.
*
* @api private
*/
Transport.prototype.onOpen = function () {
this.open = true;
this.clearCloseTimeout();
this.socket.onOpen();
};
/**
* Notifies the base when the connection with the Socket.IO server
* has been disconnected.
*
* @api private
*/
Transport.prototype.onClose = function () {
var self = this;
/* FIXME: reopen delay causing a infinit loop
this.reopenTimeout = setTimeout(function () {
self.open();
}, this.socket.options['reopen delay']);*/
this.open = false;
this.setCloseTimeout();
this.socket.onClose();
};
/**
* Generates a connection url based on the Socket.IO URL Protocol.
* See <https://github.com/learnboost/socket.io-node/> for more details.
*
* @returns {String} Connection url
* @api private
*/
Transport.prototype.prepareUrl = function () {
var options = this.socket.options;
return this.scheme() + '://'
+ options.host + ':' + options.port + '/'
+ options.resource + '/' + io.protocol
+ '/' + this.name + '/' + this.sessid;
};
/**
* Checks if the transport is ready to start a connection.
*
* @param {Socket} socket The socket instance that needs a transport
* @param {Function} fn The callback
* @api private
*/
Transport.prototype.ready = function (socket, fn) {
fn.call(this);
};
})(
'undefined' != typeof io ? io : module.exports
, 'undefined' != typeof io ? io : module.parent.exports
);
/**
* socket.io
* Copyright(c) 2011 LearnBoost <dev@learnboost.com>
* MIT Licensed
*/
(function (exports, io, global) {
/**
* Expose constructor.
*/
exports.Socket = Socket;
/**
* Create a new `Socket.IO client` which can establish a persistent
* connection with a Socket.IO enabled server.
*
* @api public
*/
function Socket (options) {
this.options = {
port: 80
, secure: false
, document: 'document' in global ? document : false
, resource: 'socket.io'
, transports: io.transports
, 'connect timeout': 10000
, 'try multiple transports': true
, 'reconnect': true
, 'reconnection delay': 500
, 'reconnection limit': Infinity
, 'reopen delay': 3000
, 'max reconnection attempts': 10
, 'sync disconnect on unload': true
, 'auto connect': true
, 'flash policy port': 10843
};
io.util.merge(this.options, options);
this.connected = false;
this.open = false;
this.connecting = false;
this.reconnecting = false;
this.namespaces = {};
this.buffer = [];
this.doBuffer = false;
if (this.options['sync disconnect on unload'] &&
(!this.isXDomain() || io.util.ua.hasCORS)) {
var self = this;
io.util.on(global, 'beforeunload', function () {
self.disconnectSync();
}, false);
}
if (this.options['auto connect']) {
this.connect();
}
};
/**
* Apply EventEmitter mixin.
*/
io.util.mixin(Socket, io.EventEmitter);
/**
* Returns a namespace listener/emitter for this socket
*
* @api public
*/
Socket.prototype.of = function (name) {
if (!this.namespaces[name]) {
this.namespaces[name] = new io.SocketNamespace(this, name);
if (name !== '') {
this.namespaces[name].packet({ type: 'connect' });
}
}
return this.namespaces[name];
};
/**
* Emits the given event to the Socket and all namespaces
*
* @api private
*/
Socket.prototype.publish = function () {
this.emit.apply(this, arguments);
var nsp;
for (var i in this.namespaces) {
if (this.namespaces.hasOwnProperty(i)) {
nsp = this.of(i);
nsp.$emit.apply(nsp, arguments);
}
}
};
/**
* Performs the handshake
*
* @api private
*/
function empty () { };
Socket.prototype.handshake = function (fn) {
var self = this
, options = this.options;
function complete (data) {
if (data instanceof Error) {
self.onError(data.message);
} else {
fn.apply(null, data.split(':'));
}
};
var url = [
'http' + (options.secure ? 's' : '') + ':/'
, options.host + ':' + options.port
, this.options.resource
, io.protocol
, io.util.query(this.options.query, 't=' + +new Date)
].join('/');
if (this.isXDomain()) {
var insertAt = document.getElementsByTagName('script')[0]
, script = document.createElement('script');
script.src = url + '&jsonp=' + io.j.length;
insertAt.parentNode.insertBefore(script, insertAt);
io.j.push(function (data) {
complete(data);
script.parentNode.removeChild(script);
});
} else {
var xhr = io.util.request();
xhr.open('GET', url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
xhr.onreadystatechange = empty;
if (xhr.status == 200) {
complete(xhr.responseText);
} else {
!self.reconnecting && self.onError(xhr.responseText);
}
}
};
xhr.send(null);
}
};
/**
* Find an available transport based on the options supplied in the constructor.
*
* @api private
*/
Socket.prototype.getTransport = function (override) {
var transports = override || this.transports, match;
for (var i = 0, transport; transport = transports[i]; i++) {
if (io.Transport[transport]
&& io.Transport[transport].check(this)
&& (!this.isXDomain() || io.Transport[transport].xdomainCheck())) {
return new io.Transport[transport](this, this.sessionid);
}
}
return null;
};
/**
* Connects to the server.
*
* @param {Function} [fn] Callback.
* @returns {io.Socket}
* @api public
*/
Socket.prototype.connect = function (fn) {
if (this.connecting) {
return this;
}
var self = this;
this.handshake(function (sid, heartbeat, close, transports) {
self.sessionid = sid;
self.closeTimeout = close * 1000;
self.heartbeatTimeout = heartbeat * 1000;
self.transports = io.util.intersect(
transports.split(',')
, self.options.transports
);
function connect (transports){
if (self.transport) self.transport.clearTimeouts();
self.transport = self.getTransport(transports);
if (!self.transport) return self.publish('connect_failed');
// once the transport is ready
self.transport.ready(self, function () {
self.connecting = true;
self.publish('connecting', self.transport.name);
self.transport.open();
if (self.options['connect timeout']) {
self.connectTimeoutTimer = setTimeout(function () {
if (!self.connected) {
self.connecting = false;
if (self.options['try multiple transports']) {
if (!self.remainingTransports) {
self.remainingTransports = self.transports.slice(0);
}
var remaining = self.remainingTransports;
while (remaining.length > 0 && remaining.splice(0,1)[0] !=
self.transport.name) {}
if (remaining.length){
connect(remaining);
} else {
self.publish('connect_failed');
}
}
}
}, self.options['connect timeout']);
}
});
}
connect();
self.once('connect', function (){
clearTimeout(self.connectTimeoutTimer);
fn && typeof fn == 'function' && fn();
});
});
return this;
};
/**
* Sends a message.
*
* @param {Object} data packet.
* @returns {io.Socket}
* @api public
*/
Socket.prototype.packet = function (data) {
if (this.connected && !this.doBuffer) {
this.transport.packet(data);
} else {
this.buffer.push(data);
}
return this;
};
/**
* Sets buffer state
*
* @api private
*/
Socket.prototype.setBuffer = function (v) {
this.doBuffer = v;
if (!v && this.connected && this.buffer.length) {
this.transport.payload(this.buffer);
this.buffer = [];
}
};
/**
* Disconnect the established connect.
*
* @returns {io.Socket}
* @api public
*/
Socket.prototype.disconnect = function () {
if (this.connected) {
if (this.open) {
this.of('').packet({ type: 'disconnect' });
}
// handle disconnection immediately
this.onDisconnect('booted');
}
return this;
};
/**
* Disconnects the socket with a sync XHR.
*
* @api private
*/
Socket.prototype.disconnectSync = function () {
// ensure disconnection
var xhr = io.util.request()
, uri = this.resource + '/' + io.protocol + '/' + this.sessionid;
xhr.open('GET', uri, true);
// handle disconnection immediately
this.onDisconnect('booted');
};
/**
* Check if we need to use cross domain enabled transports. Cross domain would
* be a different port or different domain name.
*
* @returns {Boolean}
* @api private
*/
Socket.prototype.isXDomain = function () {
var port = window.location.port ||
('https:' == window.location.protocol ? 443 : 80);
return this.options.host !== document.domain || this.options.port != port;
};
/**
* Called upon handshake.
*
* @api private
*/
Socket.prototype.onConnect = function () {
if (!this.connected) {
this.connected = true;
this.connecting = false;
if (!this.doBuffer) {
// make sure to flush the buffer
this.setBuffer(false);
}
this.emit('connect');
}
};
/**
* Called when the transport opens
*
* @api private
*/
Socket.prototype.onOpen = function () {
this.open = true;
};
/**
* Called when the transport closes.
*
* @api private
*/
Socket.prototype.onClose = function () {
this.open = false;
};
/**
* Called when the transport first opens a connection
*
* @param text
*/
Socket.prototype.onPacket = function (packet) {
this.of(packet.endpoint).onPacket(packet);
};
/**
* Handles an error.
*
* @api private
*/
Socket.prototype.onError = function (err) {
if (err && err.advice) {
if (err.advice === 'reconnect' && this.connected) {
this.disconnect();
this.reconnect();
}
}
this.publish('error', err && err.reason ? err.reason : err);
};
/**
* Called when the transport disconnects.
*
* @api private
*/
Socket.prototype.onDisconnect = function (reason) {
var wasConnected = this.connected;
this.connected = false;
this.connecting = false;
this.open = false;
if (wasConnected) {
this.transport.close();
this.transport.clearTimeouts();
this.publish('disconnect', reason);
if ('booted' != reason && this.options.reconnect && !this.reconnecting) {
this.reconnect();
}
}
};
/**
* Called upon reconnection.
*
* @api private
*/
Socket.prototype.reconnect = function () {
this.reconnecting = true;
this.reconnectionAttempts = 0;
this.reconnectionDelay = this.options['reconnection delay'];
var self = this
, maxAttempts = this.options['max reconnection attempts']
, tryMultiple = this.options['try multiple transports']
, limit = this.options['reconnection limit'];
function reset () {
if (self.connected) {
for (var i in self.namespaces) {
if (self.namespaces.hasOwnProperty(i) && '' !== i) {
self.namespaces[i].packet({ type: 'connect' });
}
}
self.publish('reconnect', self.transport.name, self.reconnectionAttempts);
}
self.removeListener('connect_failed', maybeReconnect);
self.removeListener('connect', maybeReconnect);
self.reconnecting = false;
delete self.reconnectionAttempts;
delete self.reconnectionDelay;
delete self.reconnectionTimer;
delete self.redoTransports;
self.options['try multiple transports'] = tryMultiple;
};
function maybeReconnect () {
if (!self.reconnecting) {
return;
}
if (self.connected) {
return reset();
};
if (self.connecting && self.reconnecting) {
return self.reconnectionTimer = setTimeout(maybeReconnect, 1000);
}
if (self.reconnectionAttempts++ >= maxAttempts) {
if (!self.redoTransports) {
self.on('connect_failed', maybeReconnect);
self.options['try multiple transports'] = true;
self.transport = self.getTransport();
self.redoTransports = true;
self.connect();
} else {
self.publish('reconnect_failed');
reset();
}
} else {
if (self.reconnectionDelay < limit) {
self.reconnectionDelay *= 2; // exponential back off
}
self.connect();
self.publish('reconnecting', self.reconnectionDelay, self.reconnectionAttempts);
self.reconnectionTimer = setTimeout(maybeReconnect, self.reconnectionDelay);
}
};
this.options['try multiple transports'] = false;
this.reconnectionTimer = setTimeout(maybeReconnect, this.reconnectionDelay);
this.on('connect', maybeReconnect);
};
})(
'undefined' != typeof io ? io : module.exports
, 'undefined' != typeof io ? io : module.parent.exports
, this
);
/**
* socket.io
* Copyright(c) 2011 LearnBoost <dev@learnboost.com>
* MIT Licensed
*/
(function (exports, io) {
/**
* Expose constructor.
*/
exports.SocketNamespace = SocketNamespace;
/**
* Socket namespace constructor.
*
* @constructor
* @api public
*/
function SocketNamespace (socket, name) {
this.socket = socket;
this.name = name || '';
this.flags = {};
this.json = new Flag(this, 'json');
this.ackPackets = 0;
this.acks = {};
};
/**
* Apply EventEmitter mixin.
*/
io.util.mixin(SocketNamespace, io.EventEmitter);
/**
* Copies emit since we override it
*
* @api private
*/
SocketNamespace.prototype.$emit = io.EventEmitter.prototype.emit;
/**
* Creates a new namespace, by proxying the request to the socket. This
* allows us to use the synax as we do on the server.
*
* @api public
*/
SocketNamespace.prototype.of = function () {
return this.socket.of.apply(this.socket, arguments);
};
/**
* Sends a packet.
*
* @api private
*/
SocketNamespace.prototype.packet = function (packet) {
packet.endpoint = this.name;
this.socket.packet(packet);
this.flags = {};
return this;
};
/**
* Sends a message
*
* @api public
*/
SocketNamespace.prototype.send = function (data, fn) {
var packet = {
type: this.flags.json ? 'json' : 'message'
, data: data
};
if ('function' == typeof fn) {
packet.id = ++this.ackPackets;
packet.ack = true;
this.acks[packet.id] = fn;
}
return this.packet(packet);
};
/**
* Emits an event
*
* @api public
*/
SocketNamespace.prototype.emit = function (name) {
var args = Array.prototype.slice.call(arguments, 1)
, lastArg = args[args.length - 1]
, packet = {
type: 'event'
, name: name
};
if ('function' == typeof lastArg) {
packet.id = ++this.ackPackets;
packet.ack = 'data';
this.acks[packet.id] = lastArg;
args = args.slice(0, args.length - 1);
}
packet.args = args;
return this.packet(packet);
};
/**
* Disconnects the namespace
*
* @api private
*/
SocketNamespace.prototype.disconnect = function () {
if (this.name === '') {
this.socket.disconnect();
} else {
this.packet({ type: 'disconnect' });
this.$emit('disconnect');
}
return this;
};
/**
* Handles a packet
*
* @api private
*/
SocketNamespace.prototype.onPacket = function (packet) {
var self = this;
function ack () {
self.packet({
type: 'ack'
, args: io.util.toArray(arguments)
, ackId: packet.id
});
};
switch (packet.type) {
case 'connect':
this.$emit('connect');
break;
case 'disconnect':
if (this.name === '') {
this.socket.onDisconnect(packet.reason || 'booted');
} else {
this.$emit('disconnect', packet.reason);
}
break;
case 'message':
case 'json':
var params = ['message', packet.data];
if (packet.ack == 'data') {
params.push(ack);
} else if (packet.ack) {
this.packet({ type: 'ack', ackId: packet.id });
}
this.$emit.apply(this, params);
break;
case 'event':
var params = [packet.name].concat(packet.args);
if (packet.ack == 'data')
params.push(ack);
this.$emit.apply(this, params);
break;
case 'ack':
if (this.acks[packet.ackId]) {
this.acks[packet.ackId].apply(this, packet.args);
delete this.acks[packet.ackId];
}
break;
case 'error':
if (packet.advice){
this.socket.onError(packet);
} else {
if (packet.reason == 'unauthorized') {
this.$emit('connect_failed', packet.reason);
} else {
this.$emit('error', packet.reason);
}
}
break;
}
};
/**
* Flag interface.
*
* @api private
*/
function Flag (nsp, name) {
this.namespace = nsp;
this.name = name;
};
/**
* Send a message
*
* @api public
*/
Flag.prototype.send = function () {
this.namespace.flags[this.name] = true;
this.namespace.send.apply(this.namespace, arguments);
};
/**
* Emit an event
*
* @api public
*/
Flag.prototype.emit = function () {
this.namespace.flags[this.name] = true;
this.namespace.emit.apply(this.namespace, arguments);
};
})(
'undefined' != typeof io ? io : module.exports
, 'undefined' != typeof io ? io : module.parent.exports
);
/**
* socket.io
* Copyright(c) 2011 LearnBoost <dev@learnboost.com>
* MIT Licensed
*/
(function (exports, io) {
/**
* Expose constructor.
*/
exports.websocket = WS;
/**
* The WebSocket transport uses the HTML5 WebSocket API to establish an
* persistent connection with the Socket.IO server. This transport will also
* be inherited by the FlashSocket fallback as it provides a API compatible
* polyfill for the WebSockets.
*
* @constructor
* @extends {io.Transport}
* @api public
*/
function WS (socket) {
io.Transport.apply(this, arguments);
};
/**
* Inherits from Transport.
*/
io.util.inherit(WS, io.Transport);
/**
* Transport name
*
* @api public
*/
WS.prototype.name = 'websocket';
/**
* Initializes a new `WebSocket` connection with the Socket.IO server. We attach
* all the appropriate listeners to handle the responses from the server.
*
* @returns {Transport}
* @api public
*/
WS.prototype.open = function () {
var query = io.util.query(this.socket.options.query)
, self = this
, Socket
if (!Socket) {
Socket = window.MozWebSocket || window.WebSocket;
}
this.websocket = new Socket(this.prepareUrl() + query);
this.websocket.onopen = function () {
self.onOpen();
self.socket.setBuffer(false);
};
this.websocket.onmessage = function (ev) {
self.onData(ev.data);
};
this.websocket.onclose = function () {
self.onClose();
self.socket.setBuffer(true);
};
this.websocket.onerror = function (e) {
self.onError(e);
};
return this;
};
/**
* Send a message to the Socket.IO server. The message will automatically be
* encoded in the correct message format.
*
* @returns {Transport}
* @api public
*/
WS.prototype.send = function (data) {
this.websocket.send(data);
return this;
};
/**
* Payload
*
* @api private
*/
WS.prototype.payload = function (arr) {
for (var i = 0, l = arr.length; i < l; i++) {
this.packet(arr[i]);
}
return this;
};
/**
* Disconnect the established `WebSocket` connection.
*
* @returns {Transport}
* @api public
*/
WS.prototype.close = function () {
this.websocket.close();
return this;
};
/**
* Handle the errors that `WebSocket` might be giving when we
* are attempting to connect or send messages.
*
* @param {Error} e The error.
* @api private
*/
WS.prototype.onError = function (e) {
this.socket.onError(e);
};
/**
* Returns the appropriate scheme for the URI generation.
*
* @api private
*/
WS.prototype.scheme = function () {
return this.socket.options.secure ? 'wss' : 'ws';
};
/**
* Checks if the browser has support for native `WebSockets` and that
* it's not the polyfill created for the FlashSocket transport.
*
* @return {Boolean}
* @api public
*/
WS.check = function () {
return ('WebSocket' in window && !('__addTask' in WebSocket))
|| 'MozWebSocket' in window;
};
/**
* Check if the `WebSocket` transport support cross domain communications.
*
* @returns {Boolean}
* @api public
*/
WS.xdomainCheck = function () {
return true;
};
/**
* Add the transport to your public io.transports array.
*
* @api private
*/
io.transports.push('websocket');
})(
'undefined' != typeof io ? io.Transport : module.exports
, 'undefined' != typeof io ? io : module.parent.exports
);
/**
* socket.io
* Copyright(c) 2011 LearnBoost <dev@learnboost.com>
* MIT Licensed
*/
(function (exports, io) {
/**
* Expose constructor.
*/
exports.flashsocket = Flashsocket;
/**
* The FlashSocket transport. This is a API wrapper for the HTML5 WebSocket
* specification. It uses a .swf file to communicate with the server. If you want
* to serve the .swf file from a other server than where the Socket.IO script is
* coming from you need to use the insecure version of the .swf. More information
* about this can be found on the github page.
*
* @constructor
* @extends {io.Transport.websocket}
* @api public
*/
function Flashsocket () {
io.Transport.websocket.apply(this, arguments);
};
/**
* Inherits from Transport.
*/
io.util.inherit(Flashsocket, io.Transport.websocket);
/**
* Transport name
*
* @api public
*/
Flashsocket.prototype.name = 'flashsocket';
/**
* Disconnect the established `FlashSocket` connection. This is done by adding a
* new task to the FlashSocket. The rest will be handled off by the `WebSocket`
* transport.
*
* @returns {Transport}
* @api public
*/
Flashsocket.prototype.open = function () {
var self = this
, args = arguments;
WebSocket.__addTask(function () {
io.Transport.websocket.prototype.open.apply(self, args);
});
return this;
};
/**
* Sends a message to the Socket.IO server. This is done by adding a new
* task to the FlashSocket. The rest will be handled off by the `WebSocket`
* transport.
*
* @returns {Transport}
* @api public
*/
Flashsocket.prototype.send = function () {
var self = this, args = arguments;
WebSocket.__addTask(function () {
io.Transport.websocket.prototype.send.apply(self, args);
});
return this;
};
/**
* Disconnects the established `FlashSocket` connection.
*
* @returns {Transport}
* @api public
*/
Flashsocket.prototype.close = function () {
WebSocket.__tasks.length = 0;
io.Transport.websocket.prototype.close.call(this);
return this;
};
/**
* The WebSocket fall back needs to append the flash container to the body
* element, so we need to make sure we have access to it. Or defer the call
* until we are sure there is a body element.
*
* @param {Socket} socket The socket instance that needs a transport
* @param {Function} fn The callback
* @api private
*/
Flashsocket.prototype.ready = function (socket, fn) {
function init () {
var options = socket.options
, port = options['flash policy port']
, path = [
'http' + (options.secure ? 's' : '') + ':/'
, options.host + ':' + options.port
, options.resource
, 'static/flashsocket'
, 'WebSocketMain' + (socket.isXDomain() ? 'Insecure' : '') + '.swf'
];
// Only start downloading the swf file when the checked that this browser
// actually supports it
if (!Flashsocket.loaded) {
if (typeof WEB_SOCKET_SWF_LOCATION === 'undefined') {
// Set the correct file based on the XDomain settings
WEB_SOCKET_SWF_LOCATION = path.join('/');
}
if (port !== 843) {
WebSocket.loadFlashPolicyFile('xmlsocket://' + options.host + ':' + port);
}
WebSocket.__initialize();
Flashsocket.loaded = true;
}
fn.call(self);
}
var self = this;
if (document.body) return init();
io.util.load(init);
};
/**
* Check if the FlashSocket transport is supported as it requires that the Adobe
* Flash Player plug-in version `10.0.0` or greater is installed. And also check if
* the polyfill is correctly loaded.
*
* @returns {Boolean}
* @api public
*/
Flashsocket.check = function () {
if (
typeof WebSocket == 'undefined'
|| !('__initialize' in WebSocket) || !swfobject
) return false;
return swfobject.getFlashPlayerVersion().major >= 10;
};
/**
* Check if the FlashSocket transport can be used as cross domain / cross origin
* transport. Because we can't see which type (secure or insecure) of .swf is used
* we will just return true.
*
* @returns {Boolean}
* @api public
*/
Flashsocket.xdomainCheck = function () {
return true;
};
/**
* Disable AUTO_INITIALIZATION
*/
if (typeof window != 'undefined') {
WEB_SOCKET_DISABLE_AUTO_INITIALIZATION = true;
}
/**
* Add the transport to your public io.transports array.
*
* @api private
*/
io.transports.push('flashsocket');
})(
'undefined' != typeof io ? io.Transport : module.exports
, 'undefined' != typeof io ? io : module.parent.exports
);
/* SWFObject v2.2 <http://code.google.com/p/swfobject/>
is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,...
// License: New BSD License
// Reference: http://dev.w3.org/html5/websockets/
// Reference: http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol
(function() {
if (window.WebSocket) return;
var console = window.console;
if (!console || !console.log || !console.error) {
console = {log: function(){ }, error: function(){ }};
}
if (!swfobject.hasFlashPlayerVersion("10.0.0")) {
console.error("Flash Player >= 10.0.0 is required.");
return;
}
if (location.protocol == "file:") {
console.error(
"WARNING: web-socket-js doesn't work in file:///... URL " +
"unless you set Flash Security Settings properly. " +
"Open the page via Web server i.e. http://...");
}
/**
* This class represents a faux web socket.
* @param {string} url
* @param {array or string} protocols
* @param {string} proxyHost
* @param {int} proxyPort
* @param {string} headers
*/
WebSocket = function(url, protocols, proxyHost, proxyPort, headers) {
var self = this;
self.__id = WebSocket.__nextId++;
WebSocket.__instances[self.__id] = self;
self.readyState = WebSocket.CONNECTING;
self.bufferedAmount = 0;
self.__events = {};
if (!protocols) {
protocols = [];
} else if (typeof protocols == "string") {
protocols = [protocols];
}
// Uses setTimeout() to make sure __createFlash() runs after the caller sets ws.onopen etc.
// Otherwise, when onopen fires immediately, onopen is called before it is set.
setTimeout(function() {
WebSocket.__addTask(function() {
WebSocket.__flash.create(
self.__id, url, protocols, proxyHost || null, proxyPort || 0, headers || null);
});
}, 0);
};
/**
* Send data to the web socket.
* @param {string} data The data to send to the socket.
* @return {boolean} True for success, false for failure.
*/
WebSocket.prototype.send = function(data) {
if (this.readyState == WebSocket.CONNECTING) {
throw "INVALID_STATE_ERR: Web Socket connection has not been established";
}
// We use encodeURIComponent() here, because FABridge doesn't work if
// the argument includes some characters. We don't use escape() here
// because of this:
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Functions#escape_and_unescape_Functions
// But it looks decodeURIComponent(encodeURIComponent(s)) doesn't
// preserve all Unicode characters either e.g. "\uffff" in Firefox.
// Note by wtritch: Hopefully this will not be necessary using ExternalInterface. Will require
// additional testing.
var result = WebSocket.__flash.send(this.__id, encodeURIComponent(data));
if (result < 0) { // success
return true;
} else {
this.bufferedAmount += result;
return false;
}
};
/**
* Close this web socket gracefully.
*/
WebSocket.prototype.close = function() {
if (this.readyState == WebSocket.CLOSED || this.readyState == WebSocket.CLOSING) {
return;
}
this.readyState = WebSocket.CLOSING;
WebSocket.__flash.close(this.__id);
};
/**
* Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
*
* @param {string} type
* @param {function} listener
* @param {boolean} useCapture
* @return void
*/
WebSocket.prototype.addEventListener = function(type, listener, useCapture) {
if (!(type in this.__events)) {
this.__events[type] = [];
}
this.__events[type].push(listener);
};
/**
* Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
*
* @param {string} type
* @param {function} listener
* @param {boolean} useCapture
* @return void
*/
WebSocket.prototype.removeEventListener = function(type, listener, useCapture) {
if (!(type in this.__events)) return;
var events = this.__events[type];
for (var i = events.length - 1; i >= 0; --i) {
if (events[i] === listener) {
events.splice(i, 1);
break;
}
}
};
/**
* Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
*
* @param {Event} event
* @return void
*/
WebSocket.prototype.dispatchEvent = function(event) {
var events = this.__events[event.type] || [];
for (var i = 0; i < events.length; ++i) {
events[i](event);
}
var handler = this["on" + event.type];
if (handler) handler(event);
};
/**
* Handles an event from Flash.
* @param {Object} flashEvent
*/
WebSocket.prototype.__handleEvent = function(flashEvent) {
if ("readyState" in flashEvent) {
this.readyState = flashEvent.readyState;
}
if ("protocol" in flashEvent) {
this.protocol = flashEvent.protocol;
}
var jsEvent;
if (flashEvent.type == "open" || flashEvent.type == "error") {
jsEvent = this.__createSimpleEvent(flashEvent.type);
} else if (flashEvent.type == "close") {
// TODO implement jsEvent.wasClean
jsEvent = this.__createSimpleEvent("close");
} else if (flashEvent.type == "message") {
var data = decodeURIComponent(flashEvent.message);
jsEvent = this.__createMessageEvent("message", data);
} else {
throw "unknown event type: " + flashEvent.type;
}
this.dispatchEvent(jsEvent);
};
WebSocket.prototype.__createSimpleEvent = function(type) {
if (document.createEvent && window.Event) {
var event = document.createEvent("Event");
event.initEvent(type, false, false);
return event;
} else {
return {type: type, bubbles: false, cancelable: false};
}
};
WebSocket.prototype.__createMessageEvent = function(type, data) {
if (document.createEvent && window.MessageEvent && !window.opera) {
var event = document.createEvent("MessageEvent");
event.initMessageEvent("message", false, false, data, null, null, window, null);
return event;
} else {
// IE and Opera, the latter one truncates the data parameter after any 0x00 bytes.
return {type: type, data: data, bubbles: false, cancelable: false};
}
};
/**
* Define the WebSocket readyState enumeration.
*/
WebSocket.CONNECTING = 0;
WebSocket.OPEN = 1;
WebSocket.CLOSING = 2;
WebSocket.CLOSED = 3;
WebSocket.__flash = null;
WebSocket.__instances = {};
WebSocket.__tasks = [];
WebSocket.__nextId = 0;
/**
* Load a new flash security policy file.
* @param {string} url
*/
WebSocket.loadFlashPolicyFile = function(url){
WebSocket.__addTask(function() {
WebSocket.__flash.loadManualPolicyFile(url);
});
};
/**
* Loads WebSocketMain.swf and creates WebSocketMain object in Flash.
*/
WebSocket.__initialize = function() {
if (WebSocket.__flash) return;
if (WebSocket.__swfLocation) {
// For backword compatibility.
window.WEB_SOCKET_SWF_LOCATION = WebSocket.__swfLocation;
}
if (!window.WEB_SOCKET_SWF_LOCATION) {
console.error("[WebSocket] set WEB_SOCKET_SWF_LOCATION to location of WebSocketMain.swf");
return;
}
var container = document.createElement("div");
container.id = "webSocketContainer";
// Hides Flash box. We cannot use display: none or visibility: hidden because it prevents
// Flash from loading at least in IE. So we move it out of the screen at (-100, -100).
// But this even doesn't work with Flash Lite (e.g. in Droid Incredible). So with Flash
// Lite, we put it at (0, 0). This shows 1x1 box visible at left-top corner but this is
// the best we can do as far as we know now.
container.style.position = "absolute";
if (WebSocket.__isFlashLite()) {
container.style.left = "0px";
container.style.top = "0px";
} else {
container.style.left = "-100px";
container.style.top = "-100px";
}
var holder = document.createElement("div");
holder.id = "webSocketFlash";
container.appendChild(holder);
document.body.appendChild(container);
// See this article for hasPriority:
// http://help.adobe.com/en_US/as3/mobile/WS4bebcd66a74275c36cfb8137124318eebc6-7ffd.html
swfobject.embedSWF(
WEB_SOCKET_SWF_LOCATION,
"webSocketFlash",
"1" /* width */,
"1" /* height */,
"10.0.0" /* SWF version */,
null,
null,
{hasPriority: true, swliveconnect : true, allowScriptAccess: "always"},
null,
function(e) {
if (!e.success) {
console.error("[WebSocket] swfobject.embedSWF failed");
}
});
};
/**
* Called by Flash to notify JS that it's fully loaded and ready
* for communication.
*/
WebSocket.__onFlashInitialized = function() {
// We need to set a timeout here to avoid round-trip calls
// to flash during the initialization process.
setTimeout(function() {
WebSocket.__flash = document.getElementById("webSocketFlash");
WebSocket.__flash.setCallerUrl(location.href);
WebSocket.__flash.setDebug(!!window.WEB_SOCKET_DEBUG);
for (var i = 0; i < WebSocket.__tasks.length; ++i) {
WebSocket.__tasks[i]();
}
WebSocket.__tasks = [];
}, 0);
};
/**
* Called by Flash to notify WebSockets events are fired.
*/
WebSocket.__onFlashEvent = function() {
setTimeout(function() {
try {
// Gets events using receiveEvents() instead of getting it from event object
// of Flash event. This is to make sure to keep message order.
// It seems sometimes Flash events don't arrive in the same order as they are sent.
var events = WebSocket.__flash.receiveEvents();
for (var i = 0; i < events.length; ++i) {
WebSocket.__instances[events[i].webSocketId].__handleEvent(events[i]);
}
} catch (e) {
console.error(e);
}
}, 0);
return true;
};
// Called by Flash.
WebSocket.__log = function(message) {
console.log(decodeURIComponent(message));
};
// Called by Flash.
WebSocket.__error = function(message) {
console.error(decodeURIComponent(message));
};
WebSocket.__addTask = function(task) {
if (WebSocket.__flash) {
task();
} else {
WebSocket.__tasks.push(task);
}
};
/**
* Test if the browser is running flash lite.
* @return {boolean} True if flash lite is running, false otherwise.
*/
WebSocket.__isFlashLite = function() {
if (!window.navigator || !window.navigator.mimeTypes) {
return false;
}
var mimeType = window.navigator.mimeTypes["application/x-shockwave-flash"];
if (!mimeType || !mimeType.enabledPlugin || !mimeType.enabledPlugin.filename) {
return false;
}
return mimeType.enabledPlugin.filename.match(/flashlite/i) ? true : false;
};
if (!window.WEB_SOCKET_DISABLE_AUTO_INITIALIZATION) {
if (window.addEventListener) {
window.addEventListener("load", function(){
WebSocket.__initialize();
}, false);
} else {
window.attachEvent("onload", function(){
WebSocket.__initialize();
});
}
}
})();
/**
* socket.io
* Copyright(c) 2011 LearnBoost <dev@learnboost.com>
* MIT Licensed
*/
(function (exports, io, global) {
/**
* Expose constructor.
*
* @api public
*/
exports.XHR = XHR;
/**
* XHR constructor
*
* @costructor
* @api public
*/
function XHR (socket) {
if (!socket) return;
io.Transport.apply(this, arguments);
this.sendBuffer = [];
};
/**
* Inherits from Transport.
*/
io.util.inherit(XHR, io.Transport);
/**
* Establish a connection
*
* @returns {Transport}
* @api public
*/
XHR.prototype.open = function () {
this.socket.setBuffer(false);
this.onOpen();
this.get();
// we need to make sure the request succeeds since we have no indication
// whether the request opened or not until it succeeded.
this.setCloseTimeout();
return this;
};
/**
* Check if we need to send data to the Socket.IO server, if we have data in our
* buffer we encode it and forward it to the `post` method.
*
* @api private
*/
XHR.prototype.payload = function (payload) {
var msgs = [];
for (var i = 0, l = payload.length; i < l; i++) {
msgs.push(io.parser.encodePacket(payload[i]));
}
this.send(io.parser.encodePayload(msgs));
};
/**
* Send data to the Socket.IO server.
*
* @param data The message
* @returns {Transport}
* @api public
*/
XHR.prototype.send = function (data) {
this.post(data);
return this;
};
/**
* Posts a encoded message to the Socket.IO server.
*
* @param {String} data A encoded message.
* @api private
*/
function empty () { };
XHR.prototype.post = function (data) {
var self = this;
this.socket.setBuffer(true);
function stateChange () {
if (this.readyState == 4) {
this.onreadystatechange = empty;
self.posting = false;
if (this.status == 200){
self.socket.setBuffer(false);
} else {
self.onClose();
}
}
}
function onload () {
this.onload = empty;
self.socket.setBuffer(false);
};
this.sendXHR = this.request('POST');
if (global.XDomainRequest && this.sendXHR instanceof XDomainRequest) {
this.sendXHR.onload = this.sendXHR.onerror = onload;
} else {
this.sendXHR.onreadystatechange = stateChange;
}
this.sendXHR.send(data);
};
/**
* Disconnects the established `XHR` connection.
*
* @returns {Transport}
* @api public
*/
XHR.prototype.close = function () {
this.onClose();
return this;
};
/**
* Generates a configured XHR request
*
* @param {String} url The url that needs to be requested.
* @param {String} method The method the request should use.
* @returns {XMLHttpRequest}
* @api private
*/
XHR.prototype.request = function (method) {
var req = io.util.request(this.socket.isXDomain())
, query = io.util.query(this.socket.options.query, 't=' + +new Date);
req.open(method || 'GET', this.prepareUrl() + query, true);
if (method == 'POST') {
try {
if (req.setRequestHeader) {
req.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
} else {
// XDomainRequest
req.contentType = 'text/plain';
}
} catch (e) {}
}
return req;
};
/**
* Returns the scheme to use for the transport URLs.
*
* @api private
*/
XHR.prototype.scheme = function () {
return this.socket.options.secure ? 'https' : 'http';
};
/**
* Check if the XHR transports are supported
*
* @param {Boolean} xdomain Check if we support cross domain requests.
* @returns {Boolean}
* @api public
*/
XHR.check = function (socket, xdomain) {
try {
if (io.util.request(xdomain)) {
return true;
}
} catch(e) {}
return false;
};
/**
* Check if the XHR transport supports corss domain requests.
*
* @returns {Boolean}
* @api public
*/
XHR.xdomainCheck = function () {
return XHR.check(null, true);
};
})(
'undefined' != typeof io ? io.Transport : module.exports
, 'undefined' != typeof io ? io : module.parent.exports
, this
);
/**
* socket.io
* Copyright(c) 2011 LearnBoost <dev@learnboost.com>
* MIT Licensed
*/
(function (exports, io) {
/**
* Expose constructor.
*/
exports.htmlfile = HTMLFile;
/**
* The HTMLFile transport creates a `forever iframe` based transport
* for Internet Explorer. Regular forever iframe implementations will
* continuously trigger the browsers buzy indicators. If the forever iframe
* is created inside a `htmlfile` these indicators will not be trigged.
*
* @constructor
* @extends {io.Transport.XHR}
* @api public
*/
function HTMLFile (socket) {
io.Transport.XHR.apply(this, arguments);
};
/**
* Inherits from XHR transport.
*/
io.util.inherit(HTMLFile, io.Transport.XHR);
/**
* Transport name
*
* @api public
*/
HTMLFile.prototype.name = 'htmlfile';
/**
* Creates a new ActiveX `htmlfile` with a forever loading iframe
* that can be used to listen to messages. Inside the generated
* `htmlfile` a reference will be made to the HTMLFile transport.
*
* @api private
*/
HTMLFile.prototype.get = function () {
this.doc = new ActiveXObject('htmlfile');
this.doc.open();
this.doc.write('<html></html>');
this.doc.close();
this.doc.parentWindow.s = this;
var iframeC = this.doc.createElement('div');
iframeC.className = 'socketio';
this.doc.body.appendChild(iframeC);
this.iframe = this.doc.createElement('iframe');
iframeC.appendChild(this.iframe);
var self = this
, query = io.util.query(this.socket.options.query, 't='+ +new Date);
this.iframe.src = this.prepareUrl() + query;
io.util.on(window, 'unload', function () {
self.destroy();
});
};
/**
* The Socket.IO server will write script tags inside the forever
* iframe, this function will be used as callback for the incoming
* information.
*
* @param {String} data The message
* @param {document} doc Reference to the context
* @api private
*/
HTMLFile.prototype._ = function (data, doc) {
this.onData(data);
try {
var script = doc.getElementsByTagName('script')[0];
script.parentNode.removeChild(script);
} catch (e) { }
};
/**
* Destroy the established connection, iframe and `htmlfile`.
* And calls the `CollectGarbage` function of Internet Explorer
* to release the memory.
*
* @api private
*/
HTMLFile.prototype.destroy = function () {
if (this.iframe){
try {
this.iframe.src = 'about:blank';
} catch(e){}
this.doc = null;
this.iframe.parentNode.removeChild(this.iframe);
this.iframe = null;
CollectGarbage();
}
};
/**
* Disconnects the established connection.
*
* @returns {Transport} Chaining.
* @api public
*/
HTMLFile.prototype.close = function () {
this.destroy();
return io.Transport.XHR.prototype.close.call(this);
};
/**
* Checks if the browser supports this transport. The browser
* must have an `ActiveXObject` implementation.
*
* @return {Boolean}
* @api public
*/
HTMLFile.check = function () {
if ('ActiveXObject' in window){
try {
var a = new ActiveXObject('htmlfile');
return a && io.Transport.XHR.check();
} catch(e){}
}
return false;
};
/**
* Check if cross domain requests are supported.
*
* @returns {Boolean}
* @api public
*/
HTMLFile.xdomainCheck = function () {
// we can probably do handling for sub-domains, we should
// test that it's cross domain but a subdomain here
return false;
};
/**
* Add the transport to your public io.transports array.
*
* @api private
*/
io.transports.push('htmlfile');
})(
'undefined' != typeof io ? io.Transport : module.exports
, 'undefined' != typeof io ? io : module.parent.exports
);
/**
* socket.io
* Copyright(c) 2011 LearnBoost <dev@learnboost.com>
* MIT Licensed
*/
(function (exports, io, global) {
/**
* Expose constructor.
*/
exports['xhr-polling'] = XHRPolling;
/**
* The XHR-polling transport uses long polling XHR requests to create a
* "persistent" connection with the server.
*
* @constructor
* @api public
*/
function XHRPolling () {
io.Transport.XHR.apply(this, arguments);
};
/**
* Inherits from XHR transport.
*/
io.util.inherit(XHRPolling, io.Transport.XHR);
/**
* Merge the properties from XHR transport
*/
io.util.merge(XHRPolling, io.Transport.XHR);
/**
* Transport name
*
* @api public
*/
XHRPolling.prototype.name = 'xhr-polling';
/**
* Establish a connection, for iPhone and Android this will be done once the page
* is loaded.
*
* @returns {Transport} Chaining.
* @api public
*/
XHRPolling.prototype.open = function () {
var self = this;
io.Transport.XHR.prototype.open.call(self);
return false;
};
/**
* Starts a XHR request to wait for incoming messages.
*
* @api private
*/
function empty () {};
XHRPolling.prototype.get = function () {
if (!this.open) return;
var self = this;
function stateChange () {
if (this.readyState == 4) {
this.onreadystatechange = empty;
if (this.status == 200) {
self.onData(this.responseText);
self.get();
} else {
self.onClose();
}
}
};
function onload () {
this.onload = empty;
self.onData(this.responseText);
self.get();
};
this.xhr = this.request();
if (global.XDomainRequest && this.xhr instanceof XDomainRequest) {
this.xhr.onload = this.xhr.onerror = onload;
} else {
this.xhr.onreadystatechange = stateChange;
}
this.xhr.send(null);
};
/**
* Handle the unclean close behavior.
*
* @api private
*/
XHRPolling.prototype.onClose = function () {
io.Transport.XHR.prototype.onClose.call(this);
if (this.xhr) {
this.xhr.onreadystatechange = this.xhr.onload = empty;
try {
this.xhr.abort();
} catch(e){}
this.xhr = null;
}
};
/**
* Webkit based browsers show a infinit spinner when you start a XHR request
* before the browsers onload event is called so we need to defer opening of
* the transport until the onload event is called. Wrapping the cb in our
* defer method solve this.
*
* @param {Socket} socket The socket instance that needs a transport
* @param {Function} fn The callback
* @api private
*/
XHRPolling.prototype.ready = function (socket, fn) {
var self = this;
io.util.defer(function () {
fn.call(self);
});
};
/**
* Add the transport to your public io.transports array.
*
* @api private
*/
io.transports.push('xhr-polling');
})(
'undefined' != typeof io ? io.Transport : module.exports
, 'undefined' != typeof io ? io : module.parent.exports
, this
);
/**
* socket.io
* Copyright(c) 2011 LearnBoost <dev@learnboost.com>
* MIT Licensed
*/
(function (exports, io) {
/**
* Expose constructor.
*/
exports['jsonp-polling'] = JSONPPolling;
/**
* The JSONP transport creates an persistent connection by dynamically
* inserting a script tag in the page. This script tag will receive the
* information of the Socket.IO server. When new information is received
* it creates a new script tag for the new data stream.
*
* @constructor
* @extends {io.Transport.xhr-polling}
* @api public
*/
function JSONPPolling (socket) {
io.Transport['xhr-polling'].apply(this, arguments);
this.index = io.j.length;
var self = this;
io.j.push(function (msg) {
self._(msg);
});
};
/**
* Inherits from XHR polling transport.
*/
io.util.inherit(JSONPPolling, io.Transport['xhr-polling']);
/**
* Transport name
*
* @api public
*/
JSONPPolling.prototype.name = 'jsonp-polling';
/**
* Posts a encoded message to the Socket.IO server using an iframe.
* The iframe is used because script tags can create POST based requests.
* The iframe is positioned outside of the view so the user does not
* notice it's existence.
*
* @param {String} data A encoded message.
* @api private
*/
JSONPPolling.prototype.post = function (data) {
var self = this
, query = io.util.query(
this.socket.options.query
, 't='+ (+new Date) + '&i=' + this.index
);
if (!this.form) {
var form = document.createElement('form')
, area = document.createElement('textarea')
, id = this.iframeId = 'socketio_iframe_' + this.index
, iframe;
form.className = 'socketio';
form.style.position = 'absolute';
form.style.top = '-1000px';
form.style.left = '-1000px';
form.target = id;
form.method = 'POST';
form.setAttribute('accept-charset', 'utf-8');
area.name = 'd';
form.appendChild(area);
document.body.appendChild(form);
this.form = form;
this.area = area;
}
this.form.action = this.prepareUrl() + query;
function complete () {
initIframe();
self.socket.setBuffer(false);
};
function initIframe () {
if (self.iframe) {
self.form.removeChild(self.iframe);
}
try {
// ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
iframe = document.createElement('<iframe name="'+ self.iframeId +'">');
} catch (e) {
iframe = document.createElement('iframe');
iframe.name = self.iframeId;
}
iframe.id = self.iframeId;
self.form.appendChild(iframe);
self.iframe = iframe;
};
initIframe();
this.area.value = data;
try {
this.form.submit();
} catch(e) {}
if (this.iframe.attachEvent) {
iframe.onreadystatechange = function () {
if (self.iframe.readyState == 'complete') {
complete();
}
};
} else {
this.iframe.onload = complete;
}
this.socket.setBuffer(true);
};
/**
* Creates a new JSONP poll that can be used to listen
* for messages from the Socket.IO server.
*
* @api private
*/
JSONPPolling.prototype.get = function () {
var self = this
, script = document.createElement('script')
, query = io.util.query(
this.socket.options.query
, 't='+ (+new Date) + '&i=' + this.index
);
if (this.script) {
this.script.parentNode.removeChild(this.script);
this.script = null;
}
script.async = true;
script.src = this.prepareUrl() + query;
script.onerror = function () {
self.onClose();
};
var insertAt = document.getElementsByTagName('script')[0]
insertAt.parentNode.insertBefore(script, insertAt);
this.script = script;
};
/**
* Callback function for the incoming message stream from the Socket.IO server.
*
* @param {String} data The message
* @api private
*/
JSONPPolling.prototype._ = function (msg) {
this.onData(msg);
if (this.open) {
this.get();
}
return this;
};
/**
* Checks if browser supports this transport.
*
* @return {Boolean}
* @api public
*/
JSONPPolling.check = function () {
return true;
};
/**
* Check if cross domain requests are supported
*
* @returns {Boolean}
* @api public
*/
JSONPPolling.xdomainCheck = function () {
return true;
};
/**
* Add the transport to your public io.transports array.
*
* @api private
*/
io.transports.push('jsonp-polling');
})(
'undefined' != typeof io ? io.Transport : module.exports
, 'undefined' != typeof io ? io : module.parent.exports
);
examples/chat/public/stylesheets/style.css view on Meta::CPAN
#chat,
#nickname,
#messages {
width: 600px;
}
#chat {
position: relative;
border: 1px solid #ccc;
}
#nickname,
#connecting {
position: absolute;
height: 410px;
z-index: 100;
left: 0;
top: 0;
background: #fff;
text-align: center;
width: 600px;
font: 15px Georgia;
color: #666;
display: block;
}
#nickname .wrap,
#connecting .wrap {
padding-top: 150px;
}
#nickname input {
border: 1px solid #ccc;
padding: 10px;
}
#nickname input:focus {
border-color: #999;
outline: 0;
}
#nickname #nickname-err {
color: #8b0000;
font-size: 12px;
visibility: hidden;
}
.connected #connecting {
display: none;
}
.nickname-set #nickname {
display: none;
}
#messages {
height: 380px;
background: #eee;
}
#messages em {
text-shadow: 0 1px 0 #fff;
color: #999;
}
#messages p {
padding: 0;
margin: 0;
font: 12px Helvetica, Arial;
padding: 5px 10px;
}
#messages p b {
display: inline-block;
padding-right: 10px;
}
#messages p:nth-child(even) {
background: #fafafa;
}
#messages #nicknames {
background: #ccc;
padding: 2px 4px 4px;
font: 11px Helvetica;
}
#messages #nicknames span {
color: #000;
}
#messages #nicknames b {
display: inline-block;
color: #fff;
background: #999;
padding: 3px 6px;
margin-right: 5px;
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
border-radius: 10px;
text-shadow: 0 1px 0 #666;
}
#messages #lines {
height: 355px;
overflow: auto;
overflow-x: hidden;
overflow-y: auto;
}
#messages #lines::-webkit-scrollbar {
width: 6px;
height: 6px;
}
#messages #lines::-webkit-scrollbar-button:start:decrement,
#messages #lines ::-webkit-scrollbar-button:end:increment {
display: block;
height: 10px;
}
#messages #lines::-webkit-scrollbar-button:vertical:increment {
background-color: #fff;
}
#messages #lines::-webkit-scrollbar-track-piece {
background-color: #fff;
-webkit-border-radius: 3px;
}
#messages #lines::-webkit-scrollbar-thumb:vertical {
height: 50px;
background-color: #ccc;
-webkit-border-radius: 3px;
}
#messages #lines::-webkit-scrollbar-thumb:horizontal {
width: 50px;
background-color: #fff;
-webkit-border-radius: 3px;
}
#send-message {
background: #fff;
position: relative;
}
#send-message input {
border: none;
height: 30px;
padding: 0 10px;
line-height: 30px;
vertical-align: middle;
width: 580px;
}
#send-message input:focus {
outline: 0;
}
#send-message button {
position: absolute;
top: 5px;
right: 5px;
}
button {
margin: 0;
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
display: inline-block;
text-decoration: none;
background: #43a1f7;
background: -webkit-gradient(linear, left top, left bottom, color-stop(0, #43a1f7), color-stop(1, #377ad0));
background: -webkit-linear-gradient(top, #43a1f7 0%, #377ad0 100%);
background: -moz-linear-gradient(top, #43a1f7 0%, #377ad0 100%);
background: linear-gradient(top, #43a1f7 0%, #377ad0 100%);
border: 1px solid #2e70c4;
-webkit-border-radius: 16px;
-moz-border-radius: 16px;
border-radius: 16px;
color: #fff;
font-family: "lucida grande", sans-serif;
font-size: 11px;
font-weight: normal;
line-height: 1;
padding: 3px 10px 5px 10px;
text-align: center;
text-shadow: 0 -1px 1px #2d6dc0;
}
button:hover,
button.hover {
background: darker;
background: -webkit-gradient(linear, left top, left bottom, color-stop(0, #43a1f7), color-stop(1, #2e70c4));
background: -webkit-linear-gradient(top, #43a1f7 0%, #2e70c4 100%);
background: -moz-linear-gradient(top, #43a1f7 0%, #2e70c4 100%);
background: linear-gradient(top, #43a1f7 0%, #2e70c4 100%);
border: 1px solid #2e70c4;
cursor: pointer;
text-shadow: 0 -1px 1px #2c6bbb;
}
button:active,
button.active {
background: #2e70c4;
border: 1px solid #2e70c4;
border-bottom: 1px solid #2861aa;
text-shadow: 0 -1px 1px #2b67b5;
}
button:focus,
button.focus {
outline: none;
-webkit-box-shadow: 0 1px 0 0 rgba(255,255,255,0.4), 0 0 4px 0 #377ad0;
-moz-box-shadow: 0 1px 0 0 rgba(255,255,255,0.4), 0 0 4px 0 #377ad0;
box-shadow: 0 1px 0 0 rgba(255,255,255,0.4), 0 0 4px 0 #377ad0;
}
examples/flash-policy-server view on Meta::CPAN
#!/usr/bin/env perl
use strict;
use warnings;
use AnyEvent;
use AnyEvent::Socket;
use AnyEvent::Handle;
use Getopt::Long;
die 'Must be run by root' unless $> == 0 && $< == 0;
my $domain = "localhost";
my $daemonize;
my $secure;
GetOptions(
'daemonize' => \$daemonize,
'domain=s' => \$domain,
'secure' => \$secure
) or die "Usage:\n";
my $cv = AnyEvent->condvar;
tcp_server undef, 843, sub {
my ($fh, $host, $port) = @_;
my $handle = AnyEvent::Handle->new(fh => $fh);
my $response = <<"EOF";
<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<site-control permitted-cross-domain-policies="master-only"/>
<allow-access-from domain="$domain" to-ports="*" secure="false"/>
</cross-domain-policy>
EOF
$handle->push_write($response);
};
$cv->recv;
lib/PocketIO.pm view on Meta::CPAN
package PocketIO;
use strict;
use warnings;
our $VERSION = '0.17';
use overload '&{}' => sub { shift->to_app(@_) }, fallback => 1;
use PocketIO::Exception;
use PocketIO::Resource;
use PocketIO::Pool;
sub new {
my $class = shift;
my $self = {@_};
bless $self, $class;
$self->{handler} = $self->_get_handler;
$self->{socketio} ||= {};
return $self;
}
sub to_app {
my $self = shift;
return sub { $self->call(@_) };
}
sub call {
my $self = shift;
my ($env) = @_;
my $response;
eval {
my $dispatcher = $self->_build_dispatcher(%{$self->{socketio}});
$response = $dispatcher->dispatch($env, $self->{handler});
} or do {
my $e = $@;
require Scalar::Util;
die $e unless Scalar::Util::blessed($e);
my $code = $e->code;
my $message = $e->message || 'Internal Server Error';
my @headers = (
'Content-Type' => 'text/plain',
'Content-Length' => length($message),
);
$response = [$code, \@headers, [$message]];
};
return $response;
}
sub pool {
my $self = shift;
$self->{pool} ||= PocketIO::Pool->new;
return $self->{pool};
}
sub _build_dispatcher {
my $self = shift;
return PocketIO::Resource->new(pool => $self->pool, @_);
}
sub _get_handler {
my $self = shift;
return $self->{handler} if $self->{handler};
die q{Either 'handler', 'class' or 'instance' must be specified}
unless $self->{instance} || $self->{class};
my $method = $self->{method} || 'run';
my $instance = $self->{instance}
|| do {
my $class = $self->{class};
my $path = $class;
$path =~ s{::}{/}g;
$path .= '.pm';
require $path;
$class->new;
};
return $instance->$method;
}
1;
__END__
=head1 NAME
PocketIO - Socket.IO PSGI application
=head1 SYNOPSIS
use Plack::Builder;
builder {
mount '/socket.io' => PocketIO->new(
handler => sub {
my $self = shift;
$self->on(
'message' => sub {
my $self = shift;
my ($message) = @_;
...;
}
);
$self->send({buffer => []});
}
);
$app;
};
# or
builder {
mount '/socket.io' =>
PocketIO->new(class => 'MyApp::Handler', method => 'run');
$app;
};
=head1 DESCRIPTION
L<PocketIO> is a server implementation of SocketIO in Perl, you still need
C<socket.io> javascript library on the client.
L<PocketIO> aims to have API as close as possible to the Node.js implementation
and sometimes it might look not very perlish.
=head2 How to use
First you mount L<PocketIO> as a normal L<Plack> application. It is recommended
to mount it to the C</socket.io> path since that will not require any changes on
the client side.
When the client is connected your handler is called with a L<PocketIO::Socket>
object as a first parameter.
=head2 Sending and receiving messages
A simple echo handler can look like this:
sub {
my $self = shift;
$self->on('message' => sub {
my $self = shift;
my ($message) = @_;
$self->send($message);
});
}
=head2 Sending and receiving events
Events are special messages that behave like rpc calls.
sub {
my $self = shift;
$self->on('username' => sub {
my $self = shift;
my ($nick) = @_;
...
});
$self->emit('username', 'vti');
}
=head2 Broadcasting and sending messages/events to everybody
Broadcasting is sending messages to everybody except you:
$self->broadcast->send('foo');
$self->broadcast->emit('foo');
Method C<sockets> represents all connected clients:
$self->sockets->send('foo');
$self->sockets->emit('foo');
=head2 Acknowlegements
Sometimes you want to know when the client received a message or event. In order
to achieve this just pass a callback as the last parameter:
$self->send('foo', sub {'client got message'});
$self->emit('foo', sub {'client got event'});
=head2 Storing data in the socket object
Often it is required to store some data in the client object. Instead of using
global variables there are two handy methods:
sub {
my $self = shift;
$self->set(foo => 'bar', sub { 'ready' });
$self->get('foo' => sub {
my $self = shift;
my ($err, $foo) = @_;
});
}
=head2 Namespacing
Not implemented yet.
=head2 Volatile messages
Not implemented yet.
=head2 Rooms
A room is a named group of connections for more fine-grained
broadcasts. You can subscribe or unsubscribe a socket to/from a room:
sub {
my $self = shift;
$self->join('a room');
$self->sockets->in('a room')->emit('message', data);
$self->broadcast->to('a room')->emit("other message");
}
=head1 CONFIGURATIONS
=over 4
=item handler
PocketIO->new(
handler => sub {
my $socket = shift;
$socket->on(
'message' => sub {
my $socket = shift;
}
);
$socket->send('hello');
}
);
=item class or instance, method
PocketIO->new(class => 'MyHandler', method => 'run');
# or
PocketIO->new(instance => MyHandler->new(foo => 'bar'), method => 'run');
package MyHandler;
sub new { ... } # or use Moose, Boose, Goose, Doose
sub run {
my $self = shift;
return sub {
# same code as above
}
}
Loads C<class>, creates a new object or uses a passed C<instance> and runs
C<run> method expecting it to return an anonymous subroutine.
=back
=head1 TLS/SSL
For TLS/SSL a secure proxy is needed. C<stunnel> or L<App::TLSMe> are
recommended.
=head1 SCALING
See L<PocketIO::Pool::Redis>.
=head1 DEBUGGING
Use C<POCKETIO_DEBUG> and C<POCKETIO_CONNECTION_DEBUG> variables for debugging.
=head1 METHODS
=head2 C<new>
Create a new L<PocketIO> instance.
=head2 C<pool>
Holds L<PocketIO::Pool> object by default.
=head2 C<call>
For Plack apps compatibility.
=head2 C<to_app>
Returns PSGI code reference.
=head1 SEE ALSO
More information about SocketIO you can find on the website L<http://socket.io/>, or
on the GitHub L<https://github.com/LearnBoost/Socket.IO>.
L<Protocol::SocketIO>, L<PSGI>
=head1 DEVELOPMENT
=head2 Repository
http://github.com/vti/pocketio
=head1 CREDITS
Socket.IO author(s) and contributors.
Jens Gassmann
Uwe Voelker
Oskari Okko Ojala
Jason May
Michael FiG
Peter Stuifzand
tokubass
mvgrimes
=head1 AUTHOR
Viacheslav Tykhanovskyi, C<vti@cpan.org>.
=head1 COPYRIGHT AND LICENSE
Copyright (C) 2011-2013, Viacheslav Tykhanovskyi
This program is free software, you can redistribute it and/or modify it under
the terms of the Artistic License version 2.0.
=cut
lib/PocketIO/Broadcast.pm view on Meta::CPAN
package PocketIO::Broadcast;
use strict;
use warnings;
use base 'PocketIO::Sockets';
use PocketIO::Room;
sub send {
my $self = shift;
$self->{pool}->broadcast($self->{conn}, @_);
return $self;
}
sub emit {
my $self = shift;
my $name = shift;
my $event = $self->_build_event_message($name, @_);
$self->{pool}->broadcast($self->{conn}, $event);
return $self;
}
sub to {
my $self = shift;
my ($room) = @_;
return PocketIO::Room->new(
room => $room,
conn => $self->{conn},
pool => $self->{pool}
);
}
1;
__END__
=head1 NAME
PocketIO::Sockets - Sockets class
=head1 DESCRIPTION
Used to send broadcast messages (to everybody except self).
=head1 METHODS
=head2 C<new>
Create new instance.
=head2 C<send>
Send message.
=head2 C<emit>
Emit event.
=head2 C<to>
Only broadcast to a specific room.
=cut
lib/PocketIO/Connection.pm view on Meta::CPAN
package PocketIO::Connection;
use strict;
use warnings;
use AnyEvent;
use Scalar::Util qw(blessed);
use PocketIO::Message;
use PocketIO::Socket;
use PocketIO::Sockets;
use PocketIO::Broadcast;
use constant DEBUG => $ENV{POCKETIO_CONNECTION_DEBUG};
sub new {
my $class = shift;
my $self = {@_};
bless $self, $class;
$self->{connect_timeout} ||= 30;
$self->{reconnect_timeout} ||= 15;
$self->{close_timeout} ||= 15;
$self->{on_connect_timeout} = sub { $_[0]->emit('connect_failed') };
$self->{on_reconnect_timeout} = sub { $_[0]->emit('reconnect_failed') };
$self->{on_close_timeout} = sub { $_[0]->close };
$self->{max_messages_to_stage} ||= 32;
$self->{messages} = [];
$self->{on_connect_failed} ||= sub { };
$self->{on_reconnect} ||= sub { };
$self->{on_reconnect_failed} ||= sub { };
$self->{on_message} ||= sub { };
$self->{on_disconnect} ||= sub { };
$self->{on_error} ||= sub { };
$self->{on_close} ||= sub { };
$self->{socket} ||= $self->_build_socket;
my $on_connect = delete $self->{on_connect} || sub { };
$self->{on_connect} = sub {
my $self = shift;
eval {
$on_connect->($self->{socket}, @{$self->{on_connect_args} || []});
1;
} || do {
warn "Connection error: $_";
$self->close;
};
};
DEBUG && $self->_debug('Connection created');
$self->connecting;
return $self;
}
sub new_passive {
my $class = shift;
my $self = {@_};
bless $self, $class;
return $self;
}
sub socket { $_[0]->{socket} }
sub pool { $_[0]->{pool} }
sub type { @_ > 1 ? $_[0]->{type} = $_[1] : $_[0]->{type} }
sub is_connected { $_[0]->{is_connected} }
sub connecting {
my $self = shift;
DEBUG && $self->_debug("State 'connecting'");
$self->_start_timer('connect');
}
sub reconnecting {
my $self = shift;
DEBUG && $self->_debug("State 'reconnecting'");
$self->_stop_timer('close');
$self->_start_timer('reconnect');
}
sub connected {
my $self = shift;
DEBUG && $self->_debug("State 'connected'");
$self->_stop_timer('connect');
$self->{is_connected} = 1;
my $message = PocketIO::Message->new(type => 'connect');
$self->write($message);
$self->_start_timer('close');
$self->emit('connect');
return $self;
}
sub reconnected {
my $self = shift;
DEBUG && $self->_debug("State 'reconnected'");
$self->_stop_timer('reconnect');
$self->emit('reconnect');
$self->_start_timer('close');
return $self;
}
sub disconnected {
my $self = shift;
DEBUG && $self->_debug("State 'disconnected'");
$self->_stop_timer('connect');
$self->_stop_timer('reconnect');
$self->_stop_timer('close');
$self->{data} = '';
$self->{messages} = [];
$self->{is_connected} = 0;
$self->{disconnect_timer} = AnyEvent->timer(
after => 0,
cb => sub {
return unless $self;
if ($self->{socket}) {
if (my $cb = $self->{socket}->on('disconnect')) {
$cb->($self->{socket});
}
undef $self->{socket};
}
undef $self;
}
);
return $self;
}
sub close {
my $self = shift;
my $message = PocketIO::Message->new(type => 'disconnect');
$self->write($message);
$self->emit('close');
#$self->disconnected;
return $self;
}
sub id {
my $self = shift;
$self->{id} ||= $self->_generate_id;
return $self->{id};
}
sub on {
my $self = shift;
my $event = shift;
my $name = "on_$event";
unless (@_) {
DEBUG && $self->_debug("Event 'on_$event'");
return $self->{$name};
}
$self->{$name} = $_[0];
return $self;
}
sub emit {
my $self = shift;
my $event = shift;
$event = "on_$event";
return unless exists $self->{$event};
DEBUG && $self->_debug("Emitting '$event'");
$self->{$event}->($self, @_);
return $self;
}
sub stage_message {
my $self = shift;
my ($message) = @_;
return if @{$self->{messages}} >= $self->{max_messages_to_stage};
push @{$self->{messages}}, $message;
return $self;
}
sub has_staged_messages {
my $self = shift;
return @{$self->{messages}} > 0;
}
sub staged_message {
my $self = shift;
return shift @{$self->{messages}};
}
sub send_heartbeat {
my $self = shift;
$self->{heartbeat}++;
DEBUG && $self->_debug('Send heartbeat');
my $message = PocketIO::Message->new(type => 'heartbeat');
return $self->write($message);
}
sub send {
my $self = shift;
my ($message) = @_;
$message = $self->_build_message($message);
$self->write($message);
return $self;
}
sub broadcast {
my $self = shift;
return PocketIO::Broadcast->new(conn => $self, pool => $self->pool);
}
sub sockets {
my $self = shift;
return PocketIO::Sockets->new(pool => $self->pool);
}
sub parse_message {
my $self = shift;
my ($message) = @_;
DEBUG && $self->_debug("Received '" . substr($message, 0, 80) . "'");
$message = PocketIO::Message->new->parse($message);
return unless $message;
$self->_stop_timer('close');
if ($message->is_message) {
$self->{socket}->on('message')->($self->{socket}, $message->data);
}
elsif ($message->type eq 'event') {
my $name = $message->data->{name};
my $args = $message->data->{args};
my $id = $message->id;
$self->{socket}->on($name)->(
$self->{socket},
@$args => sub {
my $message = PocketIO::Message->new(
type => 'ack',
message_id => $id,
args => [@_]
);
$self->write($message);
}
) if defined $self->{socket}->on($name);
}
elsif ($message->type eq 'heartbeat') {
# TODO
}
else {
# TODO
}
$self->_start_timer('close');
return $self;
}
sub write {
my $self = shift;
my ($bytes) = @_;
$self->_restart_timer('close');
$bytes = $bytes->to_bytes if blessed $bytes;
if ($self->{on_write}) {
DEBUG && $self->_debug("Writing '" . substr($bytes, 0, 50) . "'");
$self->emit('write', $bytes);
}
else {
DEBUG && $self->_debug("Staging '" . substr($bytes, 0, 50) . "'");
$self->stage_message($bytes);
}
}
sub _start_timer {
my $self = shift;
my ($timer) = @_;
my $timeout = $self->{"${timer}_timeout"};
return if (!defined $timeout);
DEBUG && $self->_debug("Start '${timer}_timer' ($timeout)");
$self->{"${timer}_timer"} = AnyEvent->timer(
after => $timeout,
cb => sub {
DEBUG && $self->_debug("Timeout '${timer}_timeout'");
$self->{"on_${timer}_timeout"}->($self);
}
);
}
sub _stop_timer {
my $self = shift;
my ($timer) = @_;
DEBUG && $self->_debug("Stop '${timer}_timer'");
delete $self->{"${timer}_timer"};
}
sub _restart_timer {
my $self = shift;
my ($timer) = @_;
$self->_stop_timer($timer);
$self->_start_timer($timer);
}
sub _build_message {
my $self = shift;
my ($message) = @_;
return $message if blessed $message;
return PocketIO::Message->new(data => $message);
}
sub _generate_id {
my $self = shift;
my $string = '';
for (1 .. 16) {
$string .= int(rand(10));
}
return $string;
}
sub _debug {
my $self = shift;
my ($message) = @_;
warn time . ' (' . $self->id . '): ' . $message . "\n";
}
sub _build_socket {
my $self = shift;
return PocketIO::Socket->new(conn => $self);
}
1;
__END__
=head1 NAME
PocketIO::Connection - Connection class
=head1 DESCRIPTION
L<PocketIO::Connection> is a connection class that
encapsulates all the logic for bulding and parsing Socket.IO messages. Used
internally.
=head1 METHODS
=head2 C<broadcast>
=head2 C<close>
=head2 C<connected>
=head2 C<connecting>
=head2 C<disconnected>
=head2 C<emit>
=head2 C<has_staged_messages>
=head2 C<id>
=head2 C<is_connected>
=head2 C<new>
=head2 C<on>
=head2 C<parse_message>
=head2 C<pool>
=head2 C<reconnected>
=head2 C<reconnecting>
=head2 C<send>
=head2 C<send_heartbeat>
=head2 C<socket>
=head2 C<sockets>
=head2 C<stage_message>
=head2 C<staged_message>
=head2 C<type>
=head2 C<write>
=cut
lib/PocketIO/Exception.pm view on Meta::CPAN
package PocketIO::Exception;
use strict;
use warnings;
use overload '""' => sub { $_[0]->to_string }, fallback => 1;
require Carp;
sub new {
my $class = shift;
my $self = bless {@_}, $class;
$self->{code} ||= 500;
return $self;
}
sub code { $_[0]->{code} }
sub message { $_[0]->{message} }
sub throw {
my $class = shift;
my ($code, $message) = @_;
$message = '' unless defined $message;
Carp::croak($class->new(code => $code, message => $message));
}
*as_string = \&to_string;
sub to_string { $_[0]->message }
1;
lib/PocketIO/Handle.pm view on Meta::CPAN
package PocketIO::Handle;
use strict;
use warnings;
use AnyEvent::Handle;
use constant DEBUG => $ENV{POCKETIO_HANDLE_DEBUG};
sub new {
my $class = shift;
my (%params) = @_;
my $fh = delete $params{fh};
my $self = {handle => AnyEvent::Handle->new(fh => $fh), %params};
bless $self, $class;
$self->{heartbeat_timeout} ||= 10;
$fh->autoflush;
$self->{handle}->no_delay(1);
$self->{handle}->on_eof(sub { warn "Unhandled handle eof" });
$self->{handle}->on_error(sub { warn "Unhandled handle error: $_[2]" });
# This is needed for the correct EOF handling
$self->{handle}->on_read(sub { });
return $self;
}
sub fh { $_[0]->{handle}->fh }
sub on_heartbeat {
my $self = shift;
my ($cb) = @_;
$self->{handle}->wtimeout($self->{heartbeat_timeout});
$self->{handle}->on_wtimeout($cb);
return $self;
}
sub on_read {
my $self = shift;
my ($cb) = @_;
$self->{handle}->on_read(
sub {
my $handle = shift;
$handle->push_read(
sub {
$cb->($self, $_[0]->rbuf);
}
);
}
);
return $self;
}
sub on_eof {
my $self = shift;
my ($cb) = @_;
$self->{handle}->on_eof(
sub {
$cb->($self);
}
);
return $self;
}
sub on_error {
my $self = shift;
my ($cb) = @_;
$self->{handle}->on_error(
sub {
$cb->($self);
}
);
return $self;
}
sub write {
my $self = shift;
my ($chunk, $cb) = @_;
my $handle = $self->{handle};
return $self unless $handle && $handle->fh;
$handle->push_write($chunk);
if ($cb) {
$handle->on_drain(
sub {
my $handle = shift;
$handle->on_drain(undef);
$cb->($self);
}
);
}
return $self;
}
sub close {
my $self = shift;
my $handle = delete $self->{handle};
return $self unless $handle;
$handle->wtimeout(0);
$handle->on_drain;
$handle->on_error;
$handle->on_drain(
sub {
if ($_[0]->fh) {
shutdown $_[0]->fh, 1;
close $handle->fh;
}
$_[0]->destroy;
undef $handle;
}
);
return $self;
}
1;
__END__
=head1 NAME
PocketIO::Handle - Handle
=head1 DESCRIPTION
L<PocketIO::Handle> is a wrapper on top of
L<AnyEvent::Handle>.
=head1 METHODS
=head2 C<new>
=head2 C<fh>
=head2 C<on_heartbeat>
=head2 C<on_read>
=head2 C<on_eof>
=head2 C<on_error>
=head2 C<write>
=head2 C<close>
=head1 SEE ALSO
L<AnyEvent::Handle>
=cut
lib/PocketIO/Message.pm view on Meta::CPAN
package PocketIO::Message;
use strict;
use warnings;
use base 'Protocol::SocketIO::Message';
1;
__END__
=head1 NAME
PocketIO::Message - Socket.IO message parsing and building
=head1 DESCRIPTION
L<PocketIO::Message> parsers and builds Socket.IO messages.
=cut
lib/PocketIO/Pool.pm view on Meta::CPAN
package PocketIO::Pool;
use strict;
use warnings;
use Scalar::Util qw(blessed);
use PocketIO::Connection;
use constant DEBUG => $ENV{POCKETIO_POOL_DEBUG};
sub new {
my $class = shift;
my $self = {@_};
bless $self, $class;
$self->{connections} = {};
$self->{rooms} = {};
$self->{revrooms} = {};
return $self;
}
sub find_local_connection {
my $self = shift;
my ($conn) = @_;
my $id = blessed $conn ? $conn->id : $conn;
return $self->{connections}->{$id};
}
sub find_connection {
my $self = shift;
return $self->find_local_connection(@_);
}
sub add_connection {
my $self = shift;
my $cb = pop @_;
my $conn = $self->_build_connection(@_);
$self->{connections}->{$conn->id} = $conn;
DEBUG && warn "Added connection '" . $conn->id . "'\n";
return $cb->($conn);
}
sub remove_connection {
my $self = shift;
my ($conn, $cb) = @_;
my $id = blessed $conn ? $conn->id : $conn;
delete $self->{connections}->{$id};
foreach my $room (keys %{$self->{revrooms}{$id}}) {
delete $self->{rooms}{$room}{$id};
}
delete $self->{revrooms}{$id};
DEBUG && warn "Removed connection '" . $id . "'\n";
return $cb->() if $cb;
}
sub room_join {
my $self = shift;
my $room = shift;
my $conn = shift;
my $id = blessed $conn ? $conn->id : $conn;
$conn = $self->{connections}->{$id};
$self->{rooms}{$room}{$id} = $conn;
$self->{revrooms}{$id}{$room} = $conn;
return $conn;
}
sub room_leave {
my $self = shift;
my $room = shift;
my $conn = shift;
my ($subrooms) = @_;
my $id = blessed $conn ? $conn->id : $conn;
if ($subrooms) {
DEBUG && warn "Deleting '$id' subrooms of '$room'\n";
foreach my $subroom (keys %{$self->{revrooms}{$id}}) {
if ($subroom =~ /^\Q$room\E/) {
delete $self->{rooms}{$subroom}{$id};
delete $self->{revrooms}{$id}{$subroom};
}
}
}
else {
DEBUG && warn "Deleting just '$id' room '$room'\n";
delete $self->{rooms}{$room}{$id};
delete $self->{revrooms}{$id}{$room};
}
return $conn;
}
sub send_raw {
my $self = shift;
my ($msg) = {@_};
if (defined $msg->{id}) {
# Message directly to a connection.
my $conn = $self->find_local_connection($msg->{id});
if (defined $conn) {
# Send the message here and now.
DEBUG && warn "Sending message to $msg->{id}\n";
if (defined $msg->{bytes}) {
$conn->write($msg->{bytes});
}
else {
$conn->send($msg->{message});
}
}
return $conn;
}
my @members =
defined $msg->{room}
? values %{$self->{rooms}{$msg->{room}}}
: $self->_connections;
foreach my $conn (@members) {
next unless blessed $conn && $conn->is_connected;
next if defined $msg->{invoker} && $conn->id eq $msg->{invoker}->id;
DEBUG && warn "Sending message to " . $conn->id . "\n";
$conn->socket->send($msg->{message});
}
return $self;
}
sub send {
my $self = shift;
return $self->send_raw(message => $_[0]);
}
sub broadcast {
my $self = shift;
my $invoker = shift;
return $self->send_raw(message => $_[0], invoker => $invoker);
}
sub _connections {
my $self = shift;
return values %{$self->{connections}};
}
sub _build_connection {
my $self = shift;
return PocketIO::Connection->new(
@_,
pool => $self,
on_connect_failed => sub { $self->remove_connection(@_) },
on_reconnect_failed => sub {
my $conn = shift;
$conn->disconnected;
$self->remove_connection($conn);
}
);
}
1;
__END__
=head1 NAME
PocketIO::Pool - Connection pool
=head1 DESCRIPTION
L<PocketIO::Pool> is a connection pool.
=head1 METHODS
=head2 C<new>
=head2 C<find_connection>
=head2 C<add_connection>
=head2 C<remove_connection>
=head2 C<connections>
=head2 C<send>
=head2 C<broadcast>
=cut
lib/PocketIO/Pool/Redis.pm view on Meta::CPAN
package PocketIO::Pool::Redis;
use strict;
use warnings;
use base 'PocketIO::Pool';
use AnyEvent::Redis;
use JSON;
use Scalar::Util qw(blessed);
use PocketIO::Connection;
use constant DEBUG => $ENV{POCKETIO_POOL_DEBUG};
sub new {
my $self = shift->SUPER::new(@_);
$self->{channel} ||= 'pocketio';
$self->{redis} ||= {};
$self->{pub} = $self->_create_client(%{$self->{redis}});
$self->{sub} = $self->_create_client(%{$self->{redis}});
$self->{sub}->subscribe(
$self->{channel} => sub {
my ($message, $channel) = @_;
$message = decode_json($message);
my $invoker_id = $message->{invoker};
foreach my $conn ($self->_connections) {
next unless $conn->is_connected;
next if defined $invoker_id && $conn->id eq $invoker_id;
$conn->write($message->{message});
}
}
);
return $self;
}
sub add_connection {
my $self = shift;
my $cb = pop @_;
my $conn = $self->_build_connection(@_);
$self->{connections}->{$conn->id} = $conn;
DEBUG && warn "Added connection '" . $conn->id . "'\n";
$cb->($conn);
}
sub remove_connection {
my $self = shift;
my ($conn, $cb) = @_;
my $id = blessed $conn ? $conn->id : $conn;
delete $self->{connections}->{$id};
DEBUG && warn "Removed connection '" . $id . "'\n";
$cb->() if $cb;
}
sub send {
my $self = shift;
my $message = encode_json({message => "$_[0]"});
$self->{pub}->publish($self->{channel}, $message);
return $self;
}
sub broadcast {
my $self = shift;
my $invoker = shift;
my $message = encode_json({message => "$_[0]", invoker => $invoker->id});
$self->{pub}->publish($self->{channel}, $message);
return $self;
}
sub _create_client {
my $self = shift;
return AnyEvent::Redis->new(
host => '127.0.0.1',
port => 6379,
encoding => 'utf8',
on_error => sub {
warn @_;
},
@_
);
}
1;
__END__
=head1 NAME
PocketIO::Pool::Redis - Redis class
=head1 SYNOPSIS
my $pocketio = PocketIO->new(pool => PocketIO::Pool::Redis->new);
=head1 DESCRIPTION
Uses Redis' pub/sub infrastructure
=head1 METHODS
=head2 C<new>
Create new instance.
=head2 C<add_connection>
Add new connection.
=head2 C<remove_connection>
Remove connection.
=head2 C<broadcast>
Send broadcast message.
=head2 C<send>
Send message to all client.
=cut
lib/PocketIO/Resource.pm view on Meta::CPAN
package PocketIO::Resource;
use strict;
use warnings;
use Protocol::SocketIO::Handshake;
use Protocol::SocketIO::Path;
use PocketIO::Exception;
use PocketIO::Transport::Htmlfile;
use PocketIO::Transport::JSONPPolling;
use PocketIO::Transport::WebSocket;
use PocketIO::Transport::XHRMultipart;
use PocketIO::Transport::XHRPolling;
use PocketIO::Util;
use constant DEBUG => $ENV{POCKETIO_RESOURCE_DEBUG};
my %TRANSPORTS = (
'flashsocket' => 'WebSocket',
'htmlfile' => 'Htmlfile',
'jsonp-polling' => 'JSONPPolling',
'websocket' => 'WebSocket',
# 'xhr-multipart' => 'XHRMultipart',
'xhr-polling' => 'XHRPolling',
);
sub new {
my $class = shift;
my $self = {@_};
bless $self, $class;
$self->{heartbeat_timeout} ||= 15;
$self->{close_timeout} ||= 25;
$self->{max_connections} ||= 100;
$self->{transports}
||= [qw/websocket flashsocket htmlfile xhr-polling jsonp-polling/];
return $self;
}
sub dispatch {
my $self = shift;
my ($env, $cb) = @_;
my $method = $env->{REQUEST_METHOD};
PocketIO::Exception->throw(400 => 'Unexpected method')
unless $method eq 'POST' || $method eq 'GET';
my $path_info = $env->{PATH_INFO};
my $path =
Protocol::SocketIO::Path->new(transports => $self->{transports})
->parse($path_info);
PocketIO::Exception->throw(400 => 'Cannot parse path') unless $path;
if ($path->is_handshake) {
return $self->_dispatch_handshake($env, $cb);
}
my $conn = $self->_find_connection($path->session_id);
PocketIO::Exception->throw(400 => 'Unknown session id') unless $conn;
my $transport = $self->_build_transport(
$path->transport_type,
env => $env,
conn => $conn,
handle => $self->_build_handle($env),
on_disconnect => sub { $self->{pool}->remove_connection($conn) }
);
$conn->type($path->transport_type);
my $dispatch = eval { $transport->dispatch } or do {
my $e = $@;
warn $e if DEBUG;
die $e;
};
return $dispatch;
}
sub _build_handle {
my $self = shift;
my ($env) = @_;
return PocketIO::Handle->new(
heartbeat_timeout => $self->{heartbeat_timeout},
fh => $env->{'psgix.io'}
);
}
sub _dispatch_handshake {
my $self = shift;
my ($env, $cb) = @_;
return sub {
my $respond = shift;
eval {
$self->_build_connection(
on_connect => $cb,
on_connect_args => [$env],
$self->_on_connection_created($env, $respond)
);
1;
} or do {
my $e = $@;
warn "Handshake error: $e";
PocketIO::Exception->throw(503 => 'Service unavailable');
};
};
}
sub _build_connection {
my $self = shift;
$self->{pool}->add_connection(@_);
}
sub _on_connection_created {
my $self = shift;
my ($env, $respond) = @_;
return sub {
my $conn = shift;
my $handshake = Protocol::SocketIO::Handshake->new(
session_id => $conn->id,
transports => $self->{transports},
heartbeat_timeout => $self->{heartbeat_timeout},
close_timeout => $self->{close_timeout}
)->to_bytes;
my $headers = [];
my $jsonp =
PocketIO::Util::urlencoded_param($env->{QUERY_STRING}, 'jsonp');
# XDomain request
if (defined $jsonp) {
push @$headers, 'Content-Type' => 'application/javascript';
$handshake = qq{io.j[$jsonp]("$handshake");};
}
else {
push @$headers, 'Content-Type' => 'text/plain';
}
push @$headers, 'Connection' => 'keep-alive';
push @$headers, 'Content-Length' => length($handshake);
$respond->([200, $headers, [$handshake]]);
};
}
sub _find_connection {
my $self = shift;
return $self->{pool}->find_connection(@_);
}
sub _build_transport {
my $self = shift;
my ($type, @args) = @_;
PocketIO::Exception->throw(400 => 'Transport building failed')
unless exists $TRANSPORTS{$type};
my $class = "PocketIO::Transport::$TRANSPORTS{$type}";
DEBUG && warn "Building $class\n";
return $class->new(@args);
}
1;
__END__
=head1 NAME
PocketIO::Resource - Resource class
=head1 DESCRIPTION
L<PocketIO::Resource> is a transport dispatcher.
=head1 METHODS
=head2 C<new>
=head2 C<dispatch>
=cut
lib/PocketIO/Room.pm view on Meta::CPAN
package PocketIO::Room;
use strict;
use warnings;
use PocketIO::Message;
sub new {
my $class = shift;
my $self = {@_};
bless $self, $class;
return $self;
}
sub send {
my $self = shift;
$self->{pool}->send_raw(
room => $self->{room},
invoker => $self->{conn},
message => $_[0],
);
return $self;
}
sub emit {
my $self = shift;
my $name = shift;
my $event = $self->_build_event_message($name, @_);
$self->{pool}->send_raw(
room => $self->{room},
invoker => $self->{conn},
message => $event
);
return $self;
}
sub _build_event_message {
my $self = shift;
my $event = shift;
return PocketIO::Message->new(
type => 'event',
data => {name => $event, args => [@_]}
);
}
1;
lib/PocketIO/Socket.pm view on Meta::CPAN
package PocketIO::Socket;
use strict;
use warnings;
use PocketIO::Message;
# DEPRECATED
sub send_message {&send}
sub send_broadcast { shift->broadcast->send(@_) }
sub send_broadcast_to_all { shift->sockets->send(@_) }
sub emit_broadcast { shift->broadcast->emit(@_) }
sub emit_broadcast_to_all { shift->sockets->emit(@_) }
sub new {
my $class = shift;
my $self = {@_};
bless $self, $class;
$self->{data} ||= {};
return $self;
}
sub session_id {&id}
sub id { $_[0]->{conn}->id }
sub set {
my $self = shift;
my ($key, $value, $cb) = @_;
$self->{data}->{$key} = $value;
$cb->($self) if $cb;
return $self;
}
sub get {
my $self = shift;
my ($key, $cb) = @_;
my $value = $self->{data}->{$key};
$cb->($self, undef, $value);
return $self;
}
sub on {
my $self = shift;
my $event = shift;
my $name = "on_$event";
unless (@_) {
return $self->{$name};
}
$self->{$name} = $_[0];
return $self;
}
sub emit {
my $self = shift;
my $event = shift;
$event = $self->_build_event_message($event, @_);
$self->send($event);
return $self;
}
sub send {
my $self = shift;
$self->{conn}->send(@_);
return $self;
}
sub broadcast {
my $self = shift;
return $self->{conn}->broadcast(@_);
}
sub sockets {
my $self = shift;
return $self->{conn}->sockets(@_);
}
sub close {
my $self = shift;
$self->{conn}->close;
return $self;
}
sub join {
my $self = shift;
my $room = shift;
return $self->{conn}->pool->room_join($room, $self->{conn});
}
sub leave {
my $self = shift;
my $room = shift;
return $self->{conn}->pool->room_leave($room, $self->{conn});
}
sub _build_event_message {
my $self = shift;
my $event = shift;
return PocketIO::Message->new(
type => 'event',
data => {name => $event, args => [@_]}
);
}
1;
__END__
=head1 NAME
PocketIO::Socket - Socket class
=head1 DESCRIPTION
Instance of L<PocketIO::Socket> is actually the object that you get in a
handler.
builder {
mount '/socket.io' => PocketIO->new(
handler => sub {
my $socket = shift;
# $socket is PocketIO::Socket instance
}
);
...
};
=head1 METHODS
=head2 C<new>
Create new instance.
=head2 C<close>
Close connection.
=head2 C<emit>
Emit event.
=head2 C<get>
Get attribute.
=head2 C<set>
Set atribute.
=head2 C<id>
Get session id.
=head2 C<session_id>
Same as C<id>.
=head2 C<on>
Register event.
=head2 C<send>
Send message.
=head2 C<sockets>
Get sockets object.
=head2 C<broadcast>
Get broadcasting object.
=head2 C<join>
Join the specified room.
=head2 C<leave>
Leave the specified room.
=cut