├── .gitignore ├── AUTHORS ├── LICENSE ├── README.md ├── addr.go ├── ajaxsocket.go ├── ajaxsocket_test.go ├── binarysocket.go ├── binarysocket_test.go ├── bower.json ├── client ├── dist │ ├── binarysocket.js │ └── binarysocket.min.js ├── gulpfile.js ├── package.json └── src │ ├── ajaxsocket.js │ ├── binarysocket.js │ ├── socket.js │ ├── utils.js │ ├── vendor │ └── byte-buffer.js │ └── websocket.js ├── neterror.go ├── options.go ├── options_test.go ├── sample ├── public │ └── index.html └── sample.go ├── utils.go ├── utils_test.go └── websocket.go /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | .DS_Store 3 | ._.DS_Store 4 | bower_components 5 | node_modules 6 | client/node_modules 7 | client/bower_components 8 | sample/sample 9 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | Roland Singer -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # BinarySocket - Binary Web Sockets 2 | 3 | [![GoDoc](https://godoc.org/github.com/desertbit/binarysocket?status.svg)](https://godoc.org/github.com/desertbit/binarysocket) 4 | [![Go Report Card](https://goreportcard.com/badge/github.com/desertbit/binarysocket)](https://goreportcard.com/report/github.com/desertbit/binarysocket) 5 | 6 | BinarySocket is a **real-time bidirectional binary socket library** for the web. It offers a clean, robust and efficient solution to connect webbrowsers with a go-backend in a simple way. It automatically detects supported socket layers and chooses the most suitable one. This library offers a **net.Conn interface** on the go-backend site and a similar net.Conn interface on the client javascript site. That's awesome, right? 7 | 8 | You already have a Go application using a TCP connection? Just drop in the BinarySocket package, fire up a HTTP server and that's it. No further adaptions are required in the backend. Instead of writing one backend which is responsible to communicate with web-application and another backend which communicates with other go programs, BinarySocket eliminates this duplication. 9 | 10 | In a normal scenario a high-level communication protocol is stacked on top of BinarySocket. 11 | Example: **[PAKT Project](https://github.com/desertbit/pakt)** 12 | 13 | 14 | ## Socket layers 15 | 16 | Two socket layers are supported: 17 | 18 | - **WebSockets** - This is the primary option. They are used if the webbrowser supports WebSockets defined by [RFC 6455](https://tools.ietf.org/html/rfc6455). 19 | - **AjaxSockets** - This socket layer is used as a fallback mode. 20 | 21 | ## Introduction 22 | 23 | ### Golang Backend 24 | 25 | ```go 26 | // Create a new binarysocket server. 27 | server := binarysocket.NewServer() 28 | 29 | // Set the binarysocket server handler. 30 | http.Handle("/binsocket", server) 31 | 32 | // Setup your http server. 33 | // ... 34 | 35 | // Start accepting net.Conn connections. 36 | conn, err := server.Accept() 37 | // ... 38 | ``` 39 | 40 | ### Javascript Frontend 41 | 42 | ```js 43 | var socket = BinarySocket.open("/binsocket"); 44 | 45 | socket.onOpen = function() { 46 | console.log("opened"); 47 | socket.write(BinarySocket.stringToBytes("Hello World!")); 48 | }; 49 | 50 | socket.onClose = function() { 51 | console.log("closed"); 52 | }; 53 | 54 | socket.onError = function(msg) { 55 | console.log("error:", msg); 56 | }; 57 | 58 | socket.onRead = function(data) { 59 | console.log("read:", BinarySocket.bytesToString(data)); 60 | }; 61 | ``` 62 | 63 | ## Sample 64 | 65 | Check the **[sample](sample)** directory for a simple server and client example. 66 | 67 | 68 | ## Installation 69 | 70 | ### Javascript 71 | 72 | The client javascript library is located in **[client/dist/binarysocket.min.js](client/dist/binarysocket.min.js)**. 73 | 74 | You can use bower to install the client library: 75 | 76 | `bower install --save binarysocket` 77 | 78 | ### Golang 79 | 80 | Get the source and start hacking. 81 | 82 | `go get -u github.com/desertbit/binarysocket` 83 | 84 | Import it with: 85 | 86 | ```go 87 | import "github.com/desertbit/binarysocket" 88 | ``` 89 | 90 | 91 | ## Byte Encoding 92 | 93 | BinarySocket takes care about the byte order (endianness). 94 | The default byte encoding is in network order (**big endian**). 95 | BinarySocket includes a simple javascript byte handling library. 96 | For more information check the **[ByteBuffer](https://github.com/desertbit/byte-buffer)** project. 97 | 98 | ```js 99 | var bb = BinarySocket.newByteBuffer(data) 100 | var st = BinarySocket.bytesToString(bytes) 101 | var bs = BinarySocket.stringToBytes(str) 102 | ``` 103 | 104 | 105 | ## API 106 | 107 | ### Golang 108 | 109 | For more information please check the [Go Documentation](https://godoc.org/github.com/desertbit/binarysocket). 110 | 111 | ### Javascript 112 | 113 | #### BinarySocket 114 | 115 | ```js 116 | // Open and return a new BinarySocket. 117 | // The first argument is required. It defines a host which has to start with 118 | // http:// or https:// or / for an absolute path using the current host. 119 | // The second argument defines optional options. 120 | BinarySocket.open(host, options) 121 | 122 | // Create a new ByteBuffer. 123 | // Optionally set the implicitGrowth boolean. 124 | // Wrapper for JavaScript's ArrayBuffer/DataView maintaining index and default endianness. 125 | // More information: https://github.com/desertbit/byte-buffer 126 | BinarySocket.newByteBuffer(data, implicitGrowth) 127 | 128 | // Convert an ArrayBuffer to a string. 129 | BinarySocket.bytesToString(b) 130 | 131 | // Convert a string to an ArrayBuffer. 132 | BinarySocket.stringToBytes(s) 133 | ``` 134 | 135 | #### Open Options 136 | 137 | ```js 138 | var options = { 139 | // Force a socket type. 140 | // Values: false, "WebSocket", "AjaxSocket" 141 | forceSocketType: false, 142 | 143 | // Kill the connect attempt after the timeout. 144 | connectTimeout: 10000 145 | }; 146 | ``` 147 | 148 | #### Socket 149 | 150 | ```js 151 | // Return the current socket type. 152 | // Values: "WebSocket", "AjaxSocket" 153 | socket.socketType() 154 | 155 | // Close the socket connection. 156 | socket.close() 157 | 158 | // Returns a boolean whenever the socket is closed. 159 | socket.isClosed() 160 | 161 | // Write the ArrayBuffer to the socket. 162 | socket.write(data) 163 | 164 | // Function which is triggered as soon as the connection is established. 165 | socket.onOpen = function() {} 166 | 167 | // Function which is triggered as soon as the connection closes. 168 | socket.onClose = function() {} 169 | 170 | // Function which is triggered as soon as the connection closes with an error. 171 | // An optional error message is passed. 172 | // onClose is also triggered afterwards. 173 | socket.onError = function(msg) {} 174 | 175 | // Function which is triggered as soon as new bytes are received. 176 | // The passed data is an ArrayBuffer. 177 | socket.onRead = function(data) {} 178 | ``` 179 | 180 | 181 | ## Author 182 | 183 | **Roland Singer** 184 | -------------------------------------------------------------------------------- /addr.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BinarySocket - Binary Web Sockets 3 | * Copyright (C) 2016 Roland Singer 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | 19 | package binarysocket 20 | 21 | //#################// 22 | //### addr Type ###// 23 | //#################// 24 | 25 | type addr struct { 26 | network string 27 | str string 28 | } 29 | 30 | func (a *addr) Network() string { 31 | return a.network 32 | } 33 | 34 | func (a *addr) String() string { 35 | return a.str 36 | } 37 | -------------------------------------------------------------------------------- /ajaxsocket.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BinarySocket - Binary Web Sockets 3 | * Copyright (C) 2016 Roland Singer 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | 19 | package binarysocket 20 | 21 | import ( 22 | "bufio" 23 | "fmt" 24 | "io" 25 | "net" 26 | "net/http" 27 | "strings" 28 | "sync" 29 | "time" 30 | ) 31 | 32 | //#################// 33 | //### Constants ###// 34 | //#################// 35 | 36 | const ( 37 | ajaxUIDLength = 40 38 | ajaxPollTokenLength = 20 39 | ajaxPushTokenLength = 20 40 | 41 | ajaxPollTimeout = 35 * time.Second 42 | ajaxSocketTimeout = 45 * time.Second // Has to be bigger than the poll timeout. 43 | ajaxFlushAfterTimeout = 3 * time.Millisecond 44 | 45 | ajaxHeaderSize = 2 // In Bytes 46 | ajaxHeaderStrMaxSize = 255 // In Bytes 47 | 48 | ajaxDataDelimiter = "#" 49 | 50 | ajaxRequestInit byte = 0 51 | ajaxRequestPush byte = 1 52 | ajaxRequestPoll byte = 2 53 | 54 | ajaxPollCmdData byte = 0 55 | ajaxPollCmdTimeout byte = 1 56 | ajaxPollCmdClosed byte = 2 57 | ) 58 | 59 | //#####################// 60 | //### ajaxConn Type ###// 61 | //#####################// 62 | 63 | type ajaxConn struct { 64 | io *ajaxIO 65 | bufReader *bufio.Reader 66 | bufWriter *bufio.Writer 67 | bufWriterMutex sync.Mutex 68 | bufWriterFlushT *time.Timer 69 | 70 | uid string 71 | userAgent string 72 | remoteIP string 73 | remoteAddr net.Addr 74 | localAddr net.Addr 75 | 76 | pollRequestActive bool 77 | pollRequestActiveMutex sync.Mutex 78 | pollToken string 79 | 80 | pushRequestActive bool 81 | pushRequestActiveMutex sync.Mutex 82 | pushToken string 83 | 84 | closedChan chan struct{} 85 | closeMutex sync.Mutex 86 | 87 | timeout *time.Timer 88 | } 89 | 90 | func newAjaxConn(readBufferSize, writeBufferSize int) *ajaxConn { 91 | io := newAjaxIO() 92 | 93 | c := &ajaxConn{ 94 | io: io, 95 | bufReader: bufio.NewReaderSize(io, readBufferSize), 96 | bufWriter: bufio.NewWriterSize(io, writeBufferSize), 97 | bufWriterFlushT: time.NewTimer(ajaxFlushAfterTimeout), 98 | closedChan: make(chan struct{}), 99 | timeout: time.NewTimer(ajaxSocketTimeout), 100 | } 101 | 102 | // Start the flushing buffered write routine. 103 | go func() { 104 | for { 105 | select { 106 | case <-c.bufWriterFlushT.C: 107 | func() { 108 | c.bufWriterMutex.Lock() 109 | defer c.bufWriterMutex.Unlock() 110 | 111 | if c.bufWriter.Buffered() == 0 { 112 | return 113 | } 114 | 115 | err := c.bufWriter.Flush() 116 | if err != nil { 117 | Log.Warningf("ajax: failed to flush write buffer: %v", err) 118 | c.Close() 119 | } 120 | }() 121 | 122 | case <-c.closedChan: 123 | return 124 | } 125 | } 126 | }() 127 | 128 | return c 129 | } 130 | 131 | func (c *ajaxConn) Write(data []byte) (n int, err error) { 132 | c.bufWriterMutex.Lock() 133 | defer c.bufWriterMutex.Unlock() 134 | 135 | n, err = c.bufWriter.Write(data) 136 | if err != nil { 137 | return n, err 138 | } 139 | 140 | // Reset the timer to flush the write buffer. 141 | c.bufWriterFlushT.Reset(ajaxFlushAfterTimeout) 142 | 143 | return 144 | } 145 | 146 | func (c *ajaxConn) Read(data []byte) (int, error) { 147 | return c.bufReader.Read(data) 148 | } 149 | 150 | func (c *ajaxConn) Close() error { 151 | c.closeMutex.Lock() 152 | defer c.closeMutex.Unlock() 153 | 154 | // Check if closed. 155 | select { 156 | case <-c.closedChan: 157 | return nil 158 | default: 159 | } 160 | 161 | close(c.closedChan) 162 | 163 | c.io.Close() 164 | 165 | return nil 166 | } 167 | 168 | func (c *ajaxConn) LocalAddr() net.Addr { 169 | return c.localAddr 170 | } 171 | 172 | func (c *ajaxConn) RemoteAddr() net.Addr { 173 | return c.remoteAddr 174 | } 175 | 176 | func (c *ajaxConn) SetDeadline(t time.Time) error { 177 | err := c.SetReadDeadline(t) 178 | if err != nil { 179 | return err 180 | } 181 | 182 | return c.SetWriteDeadline(t) 183 | } 184 | 185 | func (c *ajaxConn) SetReadDeadline(t time.Time) error { 186 | return c.io.SetReadDeadline(t) 187 | } 188 | 189 | func (c *ajaxConn) SetWriteDeadline(t time.Time) error { 190 | return c.io.SetWriteDeadline(t) 191 | } 192 | 193 | //###############################// 194 | //### ajaxConn Type - Private ###// 195 | //###############################// 196 | 197 | func (c *ajaxConn) lockPollRequest() bool { 198 | c.pollRequestActiveMutex.Lock() 199 | defer c.pollRequestActiveMutex.Unlock() 200 | 201 | if c.pollRequestActive { 202 | return false 203 | } 204 | 205 | c.pollRequestActive = true 206 | return true 207 | } 208 | 209 | func (c *ajaxConn) unlockPollRequest() { 210 | c.pollRequestActiveMutex.Lock() 211 | defer c.pollRequestActiveMutex.Unlock() 212 | 213 | c.pollRequestActive = false 214 | } 215 | 216 | func (c *ajaxConn) lockPushRequest() bool { 217 | c.pushRequestActiveMutex.Lock() 218 | defer c.pushRequestActiveMutex.Unlock() 219 | 220 | if c.pushRequestActive { 221 | return false 222 | } 223 | 224 | c.pushRequestActive = true 225 | return true 226 | } 227 | 228 | func (c *ajaxConn) unlockPushRequest() { 229 | c.pushRequestActiveMutex.Lock() 230 | defer c.pushRequestActiveMutex.Unlock() 231 | 232 | c.pushRequestActive = false 233 | } 234 | 235 | func (c *ajaxConn) compareIP(remoteAddr string) bool { 236 | ip, _, err := net.SplitHostPort(remoteAddr) 237 | if err != nil { 238 | return false 239 | } 240 | 241 | return c.remoteIP == ip 242 | } 243 | 244 | //###################// 245 | //### ajaxIO Type ###// 246 | //###################// 247 | 248 | type ajaxIO struct { 249 | WriteChan chan []byte 250 | ReadChan chan []byte 251 | 252 | closedChan chan struct{} 253 | readBuf []byte 254 | 255 | writeDeadline time.Time 256 | writeDeadlineMutex sync.Mutex 257 | readDeadline time.Time 258 | readDeadlineMutex sync.Mutex 259 | } 260 | 261 | func newAjaxIO() *ajaxIO { 262 | a := &ajaxIO{ 263 | WriteChan: make(chan []byte), 264 | ReadChan: make(chan []byte), 265 | closedChan: make(chan struct{}), 266 | } 267 | 268 | return a 269 | } 270 | 271 | func (a *ajaxIO) Write(data []byte) (n int, err error) { 272 | // Obtain the write timeout duration. 273 | timeoutDuration, timeoutIsZero := func() (time.Duration, bool) { 274 | a.writeDeadlineMutex.Lock() 275 | defer a.writeDeadlineMutex.Unlock() 276 | 277 | if a.writeDeadline.IsZero() { 278 | return 0, true 279 | } 280 | 281 | return a.writeDeadline.Sub(time.Now()), false 282 | }() 283 | 284 | // Only start a timeout if set (not zero). 285 | timeoutChan := make(chan struct{}) 286 | if !timeoutIsZero { 287 | if timeoutDuration > 0 { 288 | timeout := time.AfterFunc(timeoutDuration, func() { 289 | close(timeoutChan) 290 | }) 291 | defer timeout.Stop() 292 | } else { 293 | // Immediately timeout if the timeout is exceeded. 294 | close(timeoutChan) 295 | } 296 | } 297 | 298 | select { 299 | case a.WriteChan <- data: 300 | return len(data), nil 301 | case <-timeoutChan: 302 | return 0, &netError{msg: "write timeout", temporary: true, timeout: true} 303 | case <-a.closedChan: 304 | return 0, ErrClosed 305 | } 306 | } 307 | 308 | func (a *ajaxIO) Read(data []byte) (n int, err error) { 309 | // Check if there is still data present from the previous read. 310 | if len(a.readBuf) > 0 { 311 | n = copy(data, a.readBuf) 312 | a.readBuf = a.readBuf[n:] 313 | return n, nil 314 | } 315 | 316 | // Obtain the read timeout duration. 317 | timeoutDuration, timeoutIsZero := func() (time.Duration, bool) { 318 | a.readDeadlineMutex.Lock() 319 | defer a.readDeadlineMutex.Unlock() 320 | 321 | if a.readDeadline.IsZero() { 322 | return 0, true 323 | } 324 | 325 | return a.readDeadline.Sub(time.Now()), false 326 | }() 327 | 328 | // Only start a timeout if set (not zero). 329 | timeoutChan := make(chan struct{}) 330 | if !timeoutIsZero { 331 | if timeoutDuration > 0 { 332 | timeout := time.AfterFunc(timeoutDuration, func() { 333 | close(timeoutChan) 334 | }) 335 | defer timeout.Stop() 336 | } else { 337 | // Immediately timeout if the timeout is exceeded. 338 | close(timeoutChan) 339 | } 340 | } 341 | 342 | select { 343 | case buf := <-a.ReadChan: 344 | n = copy(data, buf) 345 | if n < len(buf) { 346 | a.readBuf = buf[n:] 347 | } 348 | 349 | return n, nil 350 | 351 | case <-timeoutChan: 352 | return 0, &netError{msg: "read timeout", temporary: true, timeout: true} 353 | 354 | case <-a.closedChan: 355 | return 0, ErrClosed 356 | } 357 | } 358 | 359 | func (a *ajaxIO) Close() { 360 | close(a.closedChan) 361 | } 362 | 363 | func (a *ajaxIO) SetWriteDeadline(t time.Time) error { 364 | a.writeDeadlineMutex.Lock() 365 | defer a.writeDeadlineMutex.Unlock() 366 | 367 | a.writeDeadline = t 368 | 369 | return nil 370 | } 371 | 372 | func (a *ajaxIO) SetReadDeadline(t time.Time) error { 373 | a.readDeadlineMutex.Lock() 374 | defer a.readDeadlineMutex.Unlock() 375 | 376 | a.readDeadline = t 377 | 378 | return nil 379 | } 380 | 381 | //###############// 382 | //### Private ###// 383 | //###############// 384 | 385 | func (s *Server) handleAjaxSocketRequest(rw http.ResponseWriter, req *http.Request) { 386 | remoteAddr, _ := extractRemoteAddress(req) 387 | userAgent := req.Header.Get("User-Agent") 388 | 389 | // Extract the header. 390 | reqType, headerStr, err := extractHeader(req.Body) 391 | if err != nil { 392 | httpErrLog(rw, req, http.StatusBadRequest, fmt.Errorf("ajax: failed to extract header: %v", err)) 393 | return 394 | } 395 | 396 | // Determine the request type. 397 | if reqType == ajaxRequestPush { 398 | err = s.pushAjaxRequest(headerStr, remoteAddr, userAgent, rw, req) 399 | } else if reqType == ajaxRequestPoll { 400 | err = s.pollAjaxRequest(headerStr, remoteAddr, userAgent, rw) 401 | } else if reqType == ajaxRequestInit { 402 | err = s.initAjaxRequest(remoteAddr, userAgent, rw) 403 | } else { 404 | err = fmt.Errorf("invalid request type: %v", reqType) 405 | } 406 | 407 | // Handle the error. 408 | if err != nil { 409 | httpErrLog(rw, req, http.StatusBadRequest, fmt.Errorf("ajax: %v", err)) 410 | return 411 | } 412 | } 413 | 414 | func (s *Server) initAjaxRequest(remoteAddr, userAgent string, w http.ResponseWriter) error { 415 | // Create a new ajaxsocket connection instance. 416 | a := newAjaxConn(s.options.ReadBufferSize, s.options.WriteBufferSize) 417 | a.userAgent = userAgent 418 | a.remoteAddr = &addr{ 419 | network: "tcp", 420 | str: remoteAddr, 421 | } 422 | a.localAddr = &addr{ 423 | network: "tcp", 424 | str: "unknown", // TODO: Obtain this from the request. 425 | } 426 | 427 | remoteIP, _, err := net.SplitHostPort(remoteAddr) 428 | if err != nil { 429 | return err 430 | } 431 | a.remoteIP = remoteIP 432 | 433 | var uid string 434 | err = func() error { 435 | // Lock the mutex 436 | s.ajaxSocketsMutex.Lock() 437 | defer s.ajaxSocketsMutex.Unlock() 438 | 439 | // Obtain a new unique ID. 440 | for { 441 | // Generate it. 442 | uid, err = randomString(ajaxUIDLength) 443 | if err != nil { 444 | return err 445 | } 446 | 447 | // Check if the new UID is already used. 448 | // This is very unlikely, but we have to check this! 449 | _, ok := s.ajaxSockets[uid] 450 | if !ok { 451 | // Break the loop if the UID is unique. 452 | break 453 | } 454 | } 455 | 456 | // Set the UID. 457 | a.uid = uid 458 | 459 | // Add the new ajax socket to the map. 460 | s.ajaxSockets[uid] = a 461 | return nil 462 | }() 463 | if err != nil { 464 | return err 465 | } 466 | 467 | // Start a goroutine which removes the socket again from the map 468 | // as soon as the socket is closed. 469 | go func() { 470 | <-a.closedChan 471 | 472 | // Lock the mutex 473 | s.ajaxSocketsMutex.Lock() 474 | defer s.ajaxSocketsMutex.Unlock() 475 | 476 | // Remove again from the ajax socket map. 477 | delete(s.ajaxSockets, a.uid) 478 | }() 479 | 480 | // Start a goroutine to close the socket on timeout. 481 | go func() { 482 | <-a.timeout.C 483 | a.Close() 484 | }() 485 | 486 | // Create a new poll and push token. 487 | a.pollToken, err = randomString(ajaxPollTokenLength) 488 | if err != nil { 489 | return err 490 | } 491 | a.pushToken, err = randomString(ajaxPushTokenLength) 492 | if err != nil { 493 | return err 494 | } 495 | 496 | // Tell the client the UID and the tokens. 497 | _, err = io.WriteString(w, uid+ajaxDataDelimiter+a.pollToken+ajaxDataDelimiter+a.pushToken) 498 | if err != nil { 499 | return err 500 | } 501 | 502 | // Finally handle over the new connection to the server. 503 | s.onNewSocketConn(a) 504 | 505 | return nil 506 | } 507 | 508 | func (s *Server) pushAjaxRequest(headerStr, remoteAddr, userAgent string, rw http.ResponseWriter, req *http.Request) (err error) { 509 | // Extract the uid and the push token. 510 | i := strings.Index(headerStr, ajaxDataDelimiter) 511 | if i < 0 { 512 | return fmt.Errorf("push: invalid request: missing ajax data delimiter") 513 | } 514 | uid := headerStr[:i] 515 | pushToken := headerStr[i+1:] 516 | 517 | // Obtain the ajax socket with the uid. 518 | a := func() *ajaxConn { 519 | // Lock the mutex. 520 | s.ajaxSocketsMutex.Lock() 521 | defer s.ajaxSocketsMutex.Unlock() 522 | 523 | // Obtain the ajax socket with the uid- 524 | a, ok := s.ajaxSockets[uid] 525 | if !ok { 526 | return nil 527 | } 528 | return a 529 | }() 530 | if a == nil { 531 | return fmt.Errorf("push: client requested an invalid ajax socket: uid is invalid") 532 | } 533 | 534 | // The IP addresses have to match. 535 | if !a.compareIP(remoteAddr) { 536 | return fmt.Errorf("push: invalid remote address") 537 | } 538 | 539 | // The user agents have to match. 540 | if a.userAgent != userAgent { 541 | return fmt.Errorf("push: invalid user agent") 542 | } 543 | 544 | // Only allow one push request at once. 545 | if !a.lockPushRequest() { 546 | return fmt.Errorf("push: another push request for the same socket is active") 547 | } 548 | defer a.unlockPushRequest() 549 | 550 | // Check if the push tokens match. 551 | if a.pushToken != pushToken { 552 | return fmt.Errorf("push: invalid push token") 553 | } 554 | 555 | // Create a new push token. 556 | a.pushToken, err = randomString(ajaxPushTokenLength) 557 | if err != nil { 558 | return err 559 | } 560 | 561 | // Send the new push token to the client. 562 | _, err = io.WriteString(rw, a.pushToken) 563 | if err != nil { 564 | return err 565 | } 566 | 567 | // Read from the body. 568 | var n int 569 | for { 570 | data := make([]byte, 256) 571 | n, err = req.Body.Read(data) 572 | if err != nil && err != io.EOF { 573 | return err 574 | } 575 | 576 | // Write the received data to the read channel. 577 | if n > 0 { 578 | a.io.ReadChan <- data[:n] 579 | } 580 | 581 | if err == io.EOF { 582 | return nil 583 | } 584 | 585 | if n == 0 { 586 | time.Sleep(10000 * time.Nanosecond) 587 | } 588 | } 589 | } 590 | 591 | func (s *Server) pollAjaxRequest(headerStr, remoteAddr, userAgent string, w http.ResponseWriter) (err error) { 592 | // Extract the uid and the poll token. 593 | i := strings.Index(headerStr, ajaxDataDelimiter) 594 | if i < 0 { 595 | return fmt.Errorf("poll: invalid request: missing ajax data delimiter") 596 | } 597 | uid := headerStr[:i] 598 | pollToken := headerStr[i+1:] 599 | 600 | // Obtain the ajax socket with the uid. 601 | a := func() *ajaxConn { 602 | // Lock the mutex. 603 | s.ajaxSocketsMutex.Lock() 604 | defer s.ajaxSocketsMutex.Unlock() 605 | 606 | // Obtain the ajax socket with the uid. 607 | a, ok := s.ajaxSockets[uid] 608 | if !ok { 609 | return nil 610 | } 611 | return a 612 | }() 613 | if a == nil { 614 | return fmt.Errorf("poll: client requested an invalid ajax socket: uid is invalid") 615 | } 616 | 617 | // The remote addresses have to match. 618 | if !a.compareIP(remoteAddr) { 619 | return fmt.Errorf("poll: invalid remote address") 620 | } 621 | 622 | // The user agents have to match. 623 | if a.userAgent != userAgent { 624 | return fmt.Errorf("poll: invalid user agent") 625 | } 626 | 627 | // Only allow one poll request at once. 628 | if !a.lockPollRequest() { 629 | return fmt.Errorf("poll: another poll request for the same socket is active") 630 | } 631 | defer a.unlockPollRequest() 632 | 633 | // Check if the poll tokens match. 634 | if a.pollToken != pollToken { 635 | return fmt.Errorf("poll: invalid poll token") 636 | } 637 | 638 | // Reset the socket timeout. 639 | a.timeout.Reset(ajaxSocketTimeout) 640 | 641 | // Create a new poll token. 642 | a.pollToken, err = randomString(ajaxPollTokenLength) 643 | if err != nil { 644 | return err 645 | } 646 | 647 | // Create a timeout timer for the poll. 648 | timeout := time.NewTimer(ajaxPollTimeout) 649 | defer timeout.Stop() 650 | 651 | // Send messages as soon as there are some available. 652 | select { 653 | case data := <-a.io.WriteChan: 654 | // Send the message type and the poll token length. 655 | _, err = w.Write([]byte{ajaxPollCmdData, byte(len(a.pollToken))}) 656 | if err != nil { 657 | return err 658 | } 659 | 660 | // Send the poll token. 661 | _, err = w.Write([]byte(a.pollToken)) 662 | if err != nil { 663 | return err 664 | } 665 | 666 | // Send the data. 667 | _, err = w.Write(data) 668 | if err != nil { 669 | return err 670 | } 671 | 672 | // Ensure, that after a certain timeout a new poll request has to be made. 673 | timeout.Reset(10 * time.Millisecond) 674 | 675 | // Write more data if available. 676 | WriteLoop: 677 | for { 678 | select { 679 | case data = <-a.io.WriteChan: 680 | _, err = w.Write(data) 681 | if err != nil { 682 | return err 683 | } 684 | 685 | case <-timeout.C: 686 | break WriteLoop 687 | 688 | case <-a.closedChan: 689 | break WriteLoop 690 | 691 | default: 692 | // Check if there is new data available after a short timeout. 693 | time.Sleep(500000 * time.Nanosecond) 694 | if len(a.io.WriteChan) > 0 { 695 | continue WriteLoop 696 | } 697 | 698 | break WriteLoop 699 | } 700 | } 701 | 702 | case <-timeout.C: 703 | // Tell the client that this ajax connection has reached the timeout. 704 | // Send the message type and the poll token length. 705 | _, err = w.Write([]byte{ajaxPollCmdTimeout, byte(len(a.pollToken))}) 706 | if err != nil { 707 | return err 708 | } 709 | 710 | // Send the poll token. 711 | _, err = w.Write([]byte(a.pollToken)) 712 | if err != nil { 713 | return err 714 | } 715 | 716 | case <-a.closedChan: 717 | // Tell the client that this ajax connection is closed. 718 | _, err = w.Write([]byte{ajaxPollCmdClosed}) 719 | if err != nil { 720 | return err 721 | } 722 | } 723 | 724 | return nil 725 | } 726 | 727 | func extractHeader(body io.ReadCloser) (reqType byte, headerStr string, err error) { 728 | if body == nil { 729 | return 0, "", fmt.Errorf("body is empty") 730 | } 731 | 732 | var n, totalBytesRead int 733 | header := make([]byte, ajaxHeaderSize) 734 | 735 | // Only read the header from the io Reader. 736 | for totalBytesRead < ajaxHeaderSize { 737 | n, err = body.Read(header[totalBytesRead:]) 738 | totalBytesRead += n 739 | if err != nil { 740 | if err == io.EOF { 741 | break 742 | } 743 | return 0, "", err 744 | } 745 | } 746 | 747 | if totalBytesRead != ajaxHeaderSize { 748 | return 0, "", fmt.Errorf("invalid header size") 749 | } 750 | 751 | // Extract the request type and the additional header string size. 752 | reqType = header[0] 753 | headerStrSize := int(header[1]) 754 | 755 | // Read the additional string if present. 756 | if headerStrSize > 0 { 757 | if headerStrSize > ajaxHeaderStrMaxSize { 758 | return 0, "", fmt.Errorf("invalid header string size") 759 | } 760 | 761 | header = make([]byte, headerStrSize) 762 | totalBytesRead = 0 763 | 764 | for totalBytesRead < headerStrSize { 765 | n, err = body.Read(header[totalBytesRead:]) 766 | totalBytesRead += n 767 | if err != nil { 768 | if err == io.EOF { 769 | break 770 | } 771 | return 0, "", err 772 | } 773 | } 774 | 775 | if totalBytesRead != headerStrSize { 776 | return 0, "", fmt.Errorf("invalid header string size") 777 | } 778 | 779 | // Extract the header string. 780 | headerStr = string(header) 781 | } 782 | 783 | return reqType, headerStr, nil 784 | } 785 | -------------------------------------------------------------------------------- /ajaxsocket_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BinarySocket - Binary Web Sockets 3 | * Copyright (C) 2016 Roland Singer 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | 19 | package binarysocket 20 | 21 | import ( 22 | "net" 23 | "sync" 24 | "testing" 25 | "time" 26 | 27 | "github.com/stretchr/testify/require" 28 | ) 29 | 30 | func TestAjaxIOWriteDeadline(t *testing.T) { 31 | a := newAjaxIO() 32 | 33 | err := a.SetWriteDeadline(time.Now().Add(time.Second)) 34 | require.NoError(t, err) 35 | _, err = a.Write([]byte{0, 1, 2, 3}) 36 | require.Error(t, err) 37 | require.True(t, err.(net.Error).Timeout()) 38 | 39 | err = a.SetWriteDeadline(time.Now().Add(-time.Second)) 40 | require.NoError(t, err) 41 | _, err = a.Write([]byte{0, 1, 2, 3}) 42 | require.Error(t, err) 43 | require.True(t, err.(net.Error).Timeout()) 44 | } 45 | 46 | func TestAjaxWriteDeadline(t *testing.T) { 47 | a := newAjaxConn(defaultReadBufferSize, defaultWriteBufferSize) 48 | 49 | err := a.SetWriteDeadline(time.Now().Add(time.Second)) 50 | require.NoError(t, err) 51 | _, err = a.Write(make([]byte, defaultWriteBufferSize+1)) 52 | require.Error(t, err) 53 | require.True(t, err.(net.Error).Timeout()) 54 | 55 | err = a.SetWriteDeadline(time.Now().Add(-time.Second)) 56 | require.NoError(t, err) 57 | _, err = a.Write(make([]byte, defaultWriteBufferSize+1)) 58 | require.Error(t, err) 59 | require.True(t, err.(net.Error).Timeout()) 60 | } 61 | 62 | func TestAjaxIOReadDeadline(t *testing.T) { 63 | a := newAjaxIO() 64 | data := make([]byte, 256) 65 | 66 | err := a.SetReadDeadline(time.Now().Add(time.Second)) 67 | require.NoError(t, err) 68 | _, err = a.Read(data) 69 | require.Error(t, err) 70 | require.True(t, err.(net.Error).Timeout()) 71 | 72 | err = a.SetReadDeadline(time.Now().Add(-time.Second)) 73 | require.NoError(t, err) 74 | _, err = a.Read(data) 75 | require.Error(t, err) 76 | require.True(t, err.(net.Error).Timeout()) 77 | } 78 | 79 | func TestAjaxReadDeadline(t *testing.T) { 80 | a := newAjaxConn(defaultReadBufferSize, defaultWriteBufferSize) 81 | data := make([]byte, 256) 82 | 83 | err := a.SetReadDeadline(time.Now().Add(time.Second)) 84 | require.NoError(t, err) 85 | _, err = a.Read(data) 86 | require.Error(t, err) 87 | require.True(t, err.(net.Error).Timeout()) 88 | 89 | err = a.SetReadDeadline(time.Now().Add(-time.Second)) 90 | require.NoError(t, err) 91 | _, err = a.Read(data) 92 | require.Error(t, err) 93 | require.True(t, err.(net.Error).Timeout()) 94 | } 95 | 96 | func TestAjaxIORead(t *testing.T) { 97 | var wg sync.WaitGroup 98 | a := newAjaxIO() 99 | 100 | // ###### 101 | // Test 1 102 | // ###### 103 | 104 | sampleBuf := make([]byte, 256) 105 | for x := 0; x < len(sampleBuf); x++ { 106 | sampleBuf[x] = byte(x % 256) 107 | } 108 | 109 | wg.Add(1) 110 | go func() { 111 | defer wg.Done() 112 | 113 | for i := 0; i < 100; i++ { 114 | buf := make([]byte, 256) 115 | copy(buf, sampleBuf) 116 | 117 | a.ReadChan <- buf 118 | } 119 | }() 120 | 121 | var readBytes, count int 122 | data := make([]byte, 256) 123 | 124 | for count < 100 { 125 | n, err := a.Read(data[readBytes:]) 126 | readBytes += n 127 | require.NoError(t, err) 128 | 129 | if readBytes < len(data) { 130 | continue 131 | } 132 | 133 | readBytes = 0 134 | count++ 135 | 136 | require.Equal(t, sampleBuf, data) 137 | } 138 | 139 | wg.Wait() 140 | 141 | // ###### 142 | // Test 2 143 | // ###### 144 | 145 | sampleBuf = make([]byte, 256) 146 | for x := 0; x < len(sampleBuf); x++ { 147 | sampleBuf[x] = byte(x % 256) 148 | } 149 | 150 | wg.Add(1) 151 | go func() { 152 | defer wg.Done() 153 | 154 | buf := make([]byte, 256) 155 | copy(buf, sampleBuf) 156 | 157 | a.ReadChan <- buf 158 | }() 159 | 160 | readBytes = 0 161 | data = make([]byte, 1024) 162 | 163 | for { 164 | n, err := a.Read(data[readBytes:]) 165 | readBytes += n 166 | require.NoError(t, err) 167 | 168 | if readBytes < len(sampleBuf) { 169 | continue 170 | } 171 | 172 | require.Equal(t, sampleBuf, data[:len(sampleBuf)]) 173 | break 174 | } 175 | 176 | wg.Wait() 177 | 178 | // ###### 179 | // Test 3 180 | // ###### 181 | 182 | sampleBuf = make([]byte, 256) 183 | for x := 0; x < len(sampleBuf); x++ { 184 | sampleBuf[x] = byte(x % 256) 185 | } 186 | 187 | wg.Add(1) 188 | go func() { 189 | defer wg.Done() 190 | 191 | for i := 0; i < 100; i++ { 192 | buf := make([]byte, 256) 193 | copy(buf, sampleBuf) 194 | 195 | a.ReadChan <- buf 196 | } 197 | }() 198 | 199 | readBytes = 0 200 | count = 0 201 | data = make([]byte, 256) 202 | 203 | for count < 100 { 204 | buf := make([]byte, 1) 205 | n, err := a.Read(buf) 206 | require.NoError(t, err) 207 | 208 | for i, b := range buf[:n] { 209 | data[readBytes+i] = b 210 | } 211 | 212 | readBytes += n 213 | if readBytes < len(data) { 214 | continue 215 | } 216 | 217 | readBytes = 0 218 | count++ 219 | 220 | require.Equal(t, sampleBuf, data) 221 | } 222 | 223 | wg.Wait() 224 | 225 | // ###### 226 | // Test 4 227 | // ###### 228 | 229 | sampleBuf = make([]byte, 256) 230 | for x := 0; x < len(sampleBuf); x++ { 231 | sampleBuf[x] = byte(x % 256) 232 | } 233 | 234 | wg.Add(1) 235 | go func() { 236 | defer wg.Done() 237 | 238 | for i := 0; i < 100; i++ { 239 | buf := make([]byte, 256) 240 | copy(buf, sampleBuf) 241 | 242 | a.ReadChan <- buf 243 | } 244 | }() 245 | 246 | readBytes = 0 247 | count = 0 248 | data = make([]byte, 256) 249 | 250 | for count < 100 { 251 | buf := make([]byte, 5) 252 | n, err := a.Read(buf) 253 | require.NoError(t, err) 254 | 255 | for i, b := range buf[:n] { 256 | data[readBytes+i] = b 257 | } 258 | 259 | readBytes += n 260 | if readBytes < len(data) { 261 | continue 262 | } 263 | 264 | readBytes = 0 265 | count++ 266 | 267 | require.Equal(t, sampleBuf, data) 268 | } 269 | 270 | wg.Wait() 271 | 272 | // ###### 273 | // Test 5 274 | // ###### 275 | 276 | a.Close() 277 | _, err := a.Read(data) 278 | require.Equal(t, ErrClosed, err) 279 | } 280 | -------------------------------------------------------------------------------- /binarysocket.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BinarySocket - Binary Web Sockets 3 | * Copyright (C) 2016 Roland Singer 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | 19 | // Package binarysocket is a real-time bidirectional binary socket library for the web. 20 | // It offers a clean, robust and efficient way to connect webbrowsers with a go-backend in a simple way. 21 | // It automatically detects supported socket layers and chooses the most suitable one. 22 | // This library offers a net.Conn interface on the go-backend site and a similar net.Conn 23 | // interface on the client javascript site. That's awesome, right? 24 | // You already have a Go application using a TCP connection? 25 | // Just drop in the BinarySocket package, fire up a HTTP server and that's it. 26 | // No further adaptions are required in the backend. Instead of writing one backend 27 | // which is responsible to communicate with web-application and another backend which 28 | // communicates with other go programs, BinarySocket eliminates this duplication. 29 | package binarysocket 30 | 31 | import ( 32 | "errors" 33 | "fmt" 34 | "net" 35 | "net/http" 36 | "sync" 37 | 38 | "github.com/gorilla/websocket" 39 | ) 40 | 41 | //##################// 42 | //### Constants ####// 43 | //##################// 44 | 45 | const ( 46 | acceptConnBufferSize = 10 47 | ) 48 | 49 | //##################// 50 | //### Variables ####// 51 | //##################// 52 | 53 | var ( 54 | // ErrClosed defines the error if the connection was closed. 55 | ErrClosed = errors.New("closed") 56 | ) 57 | 58 | //####################// 59 | //### Server Type ####// 60 | //####################// 61 | 62 | // Server implements the web server which handles the websocket 63 | // and ajax connections. 64 | type Server struct { 65 | options *Options 66 | acceptConnChan chan net.Conn 67 | checkOrigin func(r *http.Request) bool 68 | 69 | closedChan chan struct{} 70 | closeMutex sync.Mutex 71 | 72 | // Websocket. 73 | upgrader websocket.Upgrader 74 | 75 | // Ajaxsocket. 76 | ajaxSockets map[string]*ajaxConn 77 | ajaxSocketsMutex sync.Mutex 78 | } 79 | 80 | // NewServer creates a new server instance. 81 | // Optionally pass the BinarySocket options. 82 | func NewServer(opts ...*Options) *Server { 83 | var o *Options 84 | if len(opts) > 0 { 85 | o = opts[0] 86 | } else { 87 | o = new(Options) 88 | } 89 | o.setDefaults() 90 | 91 | s := &Server{ 92 | options: o, 93 | checkOrigin: o.CheckOrigin, 94 | closedChan: make(chan struct{}), 95 | acceptConnChan: make(chan net.Conn, acceptConnBufferSize), 96 | 97 | upgrader: websocket.Upgrader{ 98 | CheckOrigin: o.CheckOrigin, 99 | ReadBufferSize: o.ReadBufferSize, 100 | WriteBufferSize: o.WriteBufferSize, 101 | Error: httpErrLog, 102 | }, 103 | 104 | ajaxSockets: make(map[string]*ajaxConn), 105 | } 106 | 107 | return s 108 | } 109 | 110 | // Accept waits for the next client socket connection and returns a generic Conn. 111 | // Returns ErrClosed if the server is closed. 112 | func (s *Server) Accept() (net.Conn, error) { 113 | select { 114 | case conn := <-s.acceptConnChan: 115 | return conn, nil 116 | case <-s.closedChan: 117 | return nil, ErrClosed 118 | } 119 | } 120 | 121 | // IsClosed returns a boolean indicating if the server is closed. 122 | // This does not indicate the http server state. 123 | func (s *Server) IsClosed() bool { 124 | select { 125 | case <-s.closedChan: 126 | return true 127 | default: 128 | return false 129 | } 130 | } 131 | 132 | // Close the server by blocking all new incoming connections. 133 | // This does not close the http server. 134 | func (s *Server) Close() error { 135 | s.closeMutex.Lock() 136 | defer s.closeMutex.Unlock() 137 | 138 | if s.IsClosed() { 139 | return nil 140 | } 141 | 142 | close(s.closedChan) 143 | 144 | // Close all connections in the accept channel. 145 | go func() { 146 | for i := 0; i < len(s.acceptConnChan); i++ { 147 | select { 148 | case conn := <-s.acceptConnChan: 149 | go conn.Close() 150 | default: 151 | return 152 | } 153 | } 154 | }() 155 | 156 | return nil 157 | } 158 | 159 | // ServeHTTP implements the HTTP Handler interface of the http package. 160 | func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { 161 | // Block if closed. 162 | if s.IsClosed() { 163 | http.Error(w, "Service Unavailable", http.StatusServiceUnavailable) 164 | return 165 | } 166 | 167 | // Check the origin. 168 | if !s.checkOrigin(r) { 169 | httpErrLog(w, r, http.StatusForbidden, fmt.Errorf("origin not allowed")) 170 | return 171 | } 172 | 173 | // Determine the socket request type. 174 | if r.Method == "POST" { 175 | if s.options.DisableAjax { 176 | httpErrLog(w, r, http.StatusForbidden, fmt.Errorf("ajax backend is disabled")) 177 | return 178 | } 179 | 180 | // Handle the ajax request. 181 | s.handleAjaxSocketRequest(w, r) 182 | } else if r.Method == "GET" { 183 | // Handle the websocket request. 184 | s.handleWebSocketRequest(w, r) 185 | } else { 186 | httpErrLog(w, r, http.StatusMethodNotAllowed, fmt.Errorf("invalid request method: %s", r.Method)) 187 | return 188 | } 189 | } 190 | 191 | //################// 192 | //### Private ####// 193 | //################// 194 | 195 | func (s *Server) onNewSocketConn(conn net.Conn) { 196 | // Add the new connection to the accept channel. 197 | s.acceptConnChan <- conn 198 | } 199 | -------------------------------------------------------------------------------- /binarysocket_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BinarySocket - Binary Web Sockets 3 | * Copyright (C) 2016 Roland Singer 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | 19 | package binarysocket 20 | 21 | import ( 22 | "log" 23 | "net/http" 24 | "os" 25 | "testing" 26 | "time" 27 | 28 | "github.com/stretchr/testify/require" 29 | ) 30 | 31 | func TestMain(m *testing.M) { 32 | // Start the http server. 33 | go func() { 34 | err := http.ListenAndServe(":44444", nil) 35 | if err != nil { 36 | log.Fatalf("ListenAndServe: %v", err) 37 | } 38 | }() 39 | 40 | // Wait for the http server to be online. 41 | isReady := false 42 | for i := 0; i < 50; i++ { 43 | resp, err := http.Get("http://127.0.0.1:44444") 44 | if err != nil { 45 | time.Sleep(10 * time.Millisecond) 46 | continue 47 | } 48 | resp.Body.Close() 49 | 50 | isReady = true 51 | break 52 | } 53 | if !isReady { 54 | log.Fatalln("failed to start http server") 55 | } 56 | 57 | os.Exit(m.Run()) 58 | } 59 | 60 | func TestAcceptClose(t *testing.T) { 61 | server := NewServer() 62 | require.False(t, server.IsClosed()) 63 | server.Close() 64 | require.True(t, server.IsClosed()) 65 | 66 | conn, err := server.Accept() 67 | require.Nil(t, conn) 68 | require.Equal(t, ErrClosed, err) 69 | } 70 | -------------------------------------------------------------------------------- /bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "binarysocket", 3 | "version": "1.0.0", 4 | "homepage": "https://github.com/desertbit/binarysocket", 5 | "authors": [ 6 | "Roland Singer " 7 | ], 8 | "description": "Binary Web Sockets", 9 | "main": "[\"client\"]", 10 | "keywords": [ 11 | "[\"socket\"]" 12 | ], 13 | "license": "GPL3", 14 | "ignore": [ 15 | "**/*", 16 | "!client/*", 17 | "!client/**/*", 18 | "node_modules", 19 | "bower_components", 20 | "test", 21 | "tests" 22 | ] 23 | } 24 | -------------------------------------------------------------------------------- /client/dist/binarysocket.min.js: -------------------------------------------------------------------------------- 1 | var BinarySocket=function(){"use strict";!function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else{var t;"undefined"!=typeof window?t=window:"undefined"!=typeof global?t=global:"undefined"!=typeof self&&(t=self),t.ByteBuffer=e()}}(function(){return function e(t,n,r){function i(a,u){if(!n[a]){if(!t[a]){var s="function"==typeof require&&require;if(!u&&s)return s(a,!0);if(o)return o(a,!0);throw new Error("Cannot find module '"+a+"'")}var f=n[a]={exports:{}};t[a][0].call(f.exports,function(e){var n=t[a][1][e];return i(n?n:e)},f,f.exports,e,t,n,r)}return n[a].exports}for(var o="function"==typeof require&&require,a=0;athis.length&&(this._index=this.length)}},{key:"_extractBuffer",value:function(e){var t=void 0===arguments[1]?!1:arguments[1];if(e&&"undefined"!=typeof e.byteLength)return"undefined"!=typeof e.buffer?t?e.buffer.slice(0):e.buffer:t?e.slice(0):e;if(!e||"undefined"==typeof e.length)return null;if(e.constructor==String)return null;try{return new Uint8Array(e).buffer}catch(n){return null}}},{key:"front",value:function(){return this._index=0,this}},{key:"end",value:function(){return this._index=this.length,this}},{key:"seek",value:function(){var e=void 0===arguments[0]?1:arguments[0];return this.index+=e,this}},{key:"read",value:function(){var t=void 0===arguments[0]?this.available:arguments[0];if(t>this.available)throw new Error("Cannot read "+t+" byte(s), "+this.available+" available");if(0>=t)throw new RangeError("Invalid number of bytes "+t);var n=new e(this._buffer.slice(this._index,this._index+t),this.order);return this._index+=t,n}},{key:"write",value:function(e){var t;if(e instanceof Uint8Array)t=e;else{var n=this._extractBuffer(e);if(!n)throw new TypeError("Cannot write "+e+", not a sequence");t=new Uint8Array(n)}var r=this.available;if(t.byteLength>r){if(!this._implicitGrowth)throw new Error("Cannot write "+e+" using "+t.byteLength+" byte(s), "+this.available+" available");this.append(t.byteLength-r)}return this._raw.set(t,this._index),this._index+=t.byteLength,this}},{key:"readString",value:function(){var e=void 0===arguments[0]?this.available:arguments[0];if(e>this.available)throw new Error("Cannot read "+e+" byte(s), "+this.available+" available");if(0>=e)throw new RangeError("Invalid number of bytes "+e);for(var t,n,r,i=this._raw,o=[],a=0,u=null,s=this._index+e;this._indext)o[a++]=t,this._index++;else{if(194>t)throw new Error("Unexpected continuation byte");if(224>t){if(n=i[this._index+1],128>n||n>191)throw new Error("Bad continuation byte");o[a++]=((31&t)<<6)+(63&n),this._index+=2}else if(240>t){if(n=i[this._index+1],128>n||n>191)throw new Error("Bad continuation byte");if(r=i[this._index+2],128>r||r>191)throw new Error("Bad continuation byte");o[a++]=((15&t)<<12)+((63&n)<<6)+(63&r),this._index+=3}else{if(!(245>t))throw new Error("Illegal byte");if(n=i[this._index+1],128>n||n>191)throw new Error("Bad continuation byte");if(r=i[this._index+2],128>r||r>191)throw new Error("Bad continuation byte");if(u=i[this._index+3],128>u||u>191)throw new Error("Bad continuation byte");var f=((7&t)<<18)+((63&n)<<12)+((63&r)<<6)+(63&u);f-=65536,o[a++]=55296+((1047552&f)>>>10),o[a++]=56320+(1023&f),this._index+=4}}var c=65536,h=o.length;if(c>h)return String.fromCharCode.apply(String,o);for(var l=[],d=0;h>d;)l.push(String.fromCharCode.apply(String,o.slice(d,d+c))),d+=c;return l.join("")}},{key:"writeString",value:function(e){for(var t=[],n=e.length,r=0,i=0;n>r;){var o=e.charCodeAt(r);if(127>=o)t[i++]=o;else if(2047>=o)t[i++]=192|(1984&o)>>>6,t[i++]=128|63&o;else if(55295>=o||o>=57344&&65535>=o)t[i++]=224|(61440&o)>>>12,t[i++]=128|(4032&o)>>>6,t[i++]=128|63&o;else{if(r==n-1)throw new Error("Unpaired surrogate "+e[r]+" (index "+r+")");var a=e.charCodeAt(++r);if(55296>o||o>56319||56320>a||a>57343)throw new Error("Unpaired surrogate "+e[r]+" (index "+r+")");var u=((1023&o)<<10)+(1023&a)+65536;t[i++]=240|(1835008&u)>>>18,t[i++]=128|(258048&u)>>>12,t[i++]=128|(4032&u)>>>6,t[i++]=128|63&u}++r}return this.write(t),t.length}},{key:"readCString",value:function(){for(var e=this._raw,t=e.length,n=this._index;0!=e[n]&&t>n;)++n;if(t=n-this._index,t>0){var r=this.readString(t);return this.readByte(),r}return null}},{key:"writeCString",value:function(e){var t=this.writeString(e);return this.writeByte(0),++t}},{key:"prepend",value:function(e){if(0>=e)throw new RangeError("Invalid number of bytes "+e);var t=new Uint8Array(this.length+e);return t.set(this._raw,e),this._index+=e,this.buffer=t.buffer,this}},{key:"append",value:function(e){if(0>=e)throw new RangeError("Invalid number of bytes "+e);var t=new Uint8Array(this.length+e);return t.set(this._raw,0),this.buffer=t.buffer,this}},{key:"clip",value:function(){var e=void 0===arguments[0]?this._index:arguments[0],t=void 0===arguments[1]?this.length:arguments[1];0>e&&(e=this.length+e);var n=this._buffer.slice(e,t);return this._index-=e,this.buffer=n,this}},{key:"slice",value:function t(){var n=void 0===arguments[0]?0:arguments[0],r=void 0===arguments[1]?this.length:arguments[1],t=new e(this._buffer.slice(n,r),this.order);return t}},{key:"clone",value:function n(){var n=new e(this._buffer.slice(0),this.order,this.implicitGrowth);return n.index=this._index,n}},{key:"reverse",value:function(){return Array.prototype.reverse.call(this._raw),this._index=0,this}},{key:"toArray",value:function(){return Array.prototype.slice.call(this._raw,0)}},{key:"toString",value:function(){var e=this._order==this.constructor.BIG_ENDIAN?"big-endian":"little-endian";return"[ByteBuffer; Order: "+e+"; Length: "+this.length+"; Index: "+this._index+"; Available: "+this.available+"]"}},{key:"toHex",value:function(){var e=void 0===arguments[0]?" ":arguments[0];return Array.prototype.map.call(this._raw,function(e){return("00"+e.toString(16).toUpperCase()).slice(-2)}).join(e)}},{key:"toASCII",value:function(){var e=void 0===arguments[0]?" ":arguments[0],t=void 0===arguments[1]?!0:arguments[1],n=void 0===arguments[2]?"�":arguments[2],r=t?" ":"";return Array.prototype.map.call(this._raw,function(e){return 32>e||e>126?r+n:r+String.fromCharCode(e)}).join(e)}},{key:"buffer",get:function(){return this._buffer},set:function(e){this._buffer=e,this._raw=new Uint8Array(this._buffer),this._view=new DataView(this._buffer),this._sanitizeIndex()}},{key:"raw",get:function(){return this._raw}},{key:"view",get:function(){return this._view}},{key:"length",get:function(){return this._buffer.byteLength}},{key:"byteLength",get:function(){return this.length}},{key:"order",get:function(){return this._order},set:function(e){this._order=!!e}},{key:"implicitGrowth",get:function(){return this._implicitGrowth},set:function(e){this._implicitGrowth=!!e}},{key:"index",get:function(){return this._index},set:function(e){if(0>e||e>this.length)throw new RangeError("Invalid index "+e+", should be between 0 and "+this.length);this._index=e}},{key:"available",get:function(){return this.length-this._index}}],[{key:"LITTLE_ENDIAN",value:!0,enumerable:!0},{key:"BIG_ENDIAN",value:!1,enumerable:!0}]),e}(),a=function(e,t){return function(){var n=void 0===arguments[0]?this._order:arguments[0];if(t>this.available)throw new Error("Cannot read "+t+" byte(s), "+this.available+" available");var r=this._view[e](this._index,n);return this._index+=t,r}},u=function(e,t){return function(n){var r=void 0===arguments[1]?this._order:arguments[1],i=this.available;if(t>i){if(!this._implicitGrowth)throw new Error("Cannot write "+n+" using "+t+" byte(s), "+i+" available");this.append(t-i)}return this._view[e](this._index,n,r),this._index+=t,this}};o.prototype.readByte=a("getInt8",1),o.prototype.readUnsignedByte=a("getUint8",1),o.prototype.readShort=a("getInt16",2),o.prototype.readUnsignedShort=a("getUint16",2),o.prototype.readInt=a("getInt32",4),o.prototype.readUnsignedInt=a("getUint32",4),o.prototype.readFloat=a("getFloat32",4),o.prototype.readDouble=a("getFloat64",8),o.prototype.writeByte=u("setInt8",1),o.prototype.writeUnsignedByte=u("setUint8",1),o.prototype.writeShort=u("setInt16",2),o.prototype.writeUnsignedShort=u("setUint16",2),o.prototype.writeInt=u("setInt32",4),o.prototype.writeUnsignedInt=u("setUint32",4),o.prototype.writeFloat=u("setFloat32",4),o.prototype.writeDouble=u("setFloat64",8),t.exports=o},{}]},{},[1])(1)});var e={extend:function(){for(var e=1;e0&&(s=r.length),u.writeByte(s),s>0&&u.writeString(r),i&&i.byteLength>0&&u.write(i),g=n(t,h,u.buffer,function(e){g=!1,a&&a(e)},function(e){g=!1,o(e)})}var u,s,f,c,h=3e4,l=45e3,d="#",y={Init:0,Push:1,Poll:2},v={Data:0,Timeout:1,Closed:2},w={},p=!1,g=!1,b=!1,_=[];c=function(){var e=new ByteBuffer(3,ByteBuffer.BIG_ENDIAN,!0);e.writeByte(y.Poll);var r=u+d+s;e.writeByte(r.length),e.writeString(r),p=n(t,l,e.buffer,function(e){p=!1;var t=new ByteBuffer(e,ByteBuffer.BIG_ENDIAN);if(t.length<1)return void o("ajax socket: poll: invalid server response");var n=t.readByte();if(n==v.Closed)return void i();if(t.length<2)return void o("ajax socket: poll: invalid server response");var r=t.readByte();return s=t.readString(r),n==v.Timeout?void c():(c(),t.clip(),void w.onMessage(t.buffer))},function(e){p=!1,o(e)})};var B=e.throttle(function(){if(!b){var e,t=0;for(e=0;e<_.length;e++)t+=_[e].byteLength;var n=new ByteBuffer(t,ByteBuffer.BIG_ENDIAN);for(e=0;e<_.length;e++)n.write(_[e]);_=[],b=!0,a(y.Push,u+d+f,n.buffer,function(e){if(b=!1,!e||e.byteLength<=0)return void o("ajax socket: push: invalid server response");var t=new ByteBuffer(e,ByteBuffer.BIG_ENDIAN);f=t.readString(),_.length>0&&B()})}},50);return w.open=function(){a(y.Init,null,null,function(e){if(!e||e.byteLength<=0)return void o("ajax socket: open: invalid server response");var t=new ByteBuffer(e,ByteBuffer.BIG_ENDIAN);e=t.readString();var n=e.split(d);return 3!==n.length?void o("ajax socket: failed to obtain uid and tokens"):(u=n[0],s=n[1],f=n[2],c(),void w.onOpen())})},w.send=function(e){_.push(e),B()},w.close=function(){r()},w},c={WebSocket:"WebSocket",AjaxSocket:"AjaxSocket"},h={forceSocketType:!1,connectTimeout:1e4},l=!1,d={socketType:function(){return u.socketType},close:function(){u.close(),i()},isClosed:function(){return l},write:function(e){return l?void console.log("BinarySocket: failed to write: the socket is closed"):e instanceof ArrayBuffer?void(0!==e.byteLength&&u.send(e)):void console.log("BinarySocket: failed to write data: data is not of type ArrayBuffer")},onRead:function(e){}};return window.ArrayBuffer?(n=e.extend({},h,n),t.match("^/")?t=window.location.protocol+"//"+window.location.host+t:t||(t=window.location.protocol+"//"+window.location.host),t.match("^http://")||t.match("^https://")?(a(),d):void console.log("BinarySocket: invalid host: missing 'http://' or 'https://'!")):void console.log("BinarySocket: ArrayBuffers are not supported by this browser!")};return{open:t,newByteBuffer:function(e,t){return new ByteBuffer(e,ByteBuffer.BIG_ENDIAN,t)},bytesToString:function(e){var t=this.newByteBuffer(e);return t.readString()},stringToBytes:function(e){var t=this.newByteBuffer(1,!0);return t.writeString(e),t.buffer}}}(); -------------------------------------------------------------------------------- /client/gulpfile.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var gulp = require('gulp'), 4 | rename = require('gulp-rename'), 5 | sourcemaps = require('gulp-sourcemaps'), 6 | uglify = require('gulp-uglify'), 7 | fileinclude = require('gulp-file-include'); 8 | 9 | 10 | 11 | gulp.task('js', function () { 12 | gulp.src(['src/binarysocket.js']) 13 | .pipe(fileinclude({ 14 | prefix: '@@', 15 | basepath: '@file' 16 | })) 17 | .pipe(sourcemaps.init()) 18 | .pipe(sourcemaps.write()) 19 | .pipe(gulp.dest('./dist/')); 20 | }); 21 | 22 | gulp.task('js-min', function () { 23 | gulp.src(['src/binarysocket.js']) 24 | .pipe(rename("binarysocket.min.js")) 25 | .pipe(fileinclude({ 26 | prefix: '@@', 27 | basepath: '@file' 28 | })) 29 | .pipe(uglify()) 30 | .pipe(gulp.dest('./dist/')); 31 | }); 32 | 33 | gulp.task('watch', ['default'], function () { 34 | gulp.watch(['./src/*.js', './src/**/*.js'], ['js']); 35 | }); 36 | 37 | gulp.task('default', ['js', 'js-min'], function() { 38 | 39 | }); 40 | -------------------------------------------------------------------------------- /client/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "binarysocket", 3 | "version": "1.0.0", 4 | "description": "Binary Web Sockets", 5 | "main": "gulpfile.js", 6 | "dependencies": { 7 | "gulp": "^3.9.1", 8 | "gulp-file-include": "^0.9.0", 9 | "gulp-rename": "^1.2.2", 10 | "gulp-sourcemaps": "^1.5.2", 11 | "gulp-uglify": "^1.5.3" 12 | }, 13 | "devDependencies": {}, 14 | "scripts": { 15 | "test": "echo \"Error: no test specified\" && exit 1" 16 | }, 17 | "author": "Roland Singer ", 18 | "license": "GPL3" 19 | } 20 | -------------------------------------------------------------------------------- /client/src/ajaxsocket.js: -------------------------------------------------------------------------------- 1 | /* 2 | * BinarySocket - Binary Web Sockets 3 | * Copyright (C) 2016 Roland Singer 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | 19 | /* 20 | * This code lives inside the BinarySocket function. 21 | */ 22 | 23 | var newAjaxSocket = function () { 24 | /* 25 | * Constants 26 | */ 27 | 28 | var sendTimeout = 30000, 29 | pollTimeout = 45000; 30 | 31 | var DataDelimiter = '#'; 32 | 33 | var RequestType = { 34 | Init: 0, 35 | Push: 1, 36 | Poll: 2 37 | }; 38 | 39 | var PollType = { 40 | Data: 0, 41 | Timeout: 1, 42 | Closed: 2 43 | }; 44 | 45 | 46 | 47 | /* 48 | * Variables 49 | */ 50 | 51 | var s = {}, 52 | uid, pollToken, pushToken, 53 | pollXhr = false, 54 | sendXhr = false, 55 | poll, 56 | pushActive = false, 57 | pushBuffer = []; 58 | 59 | 60 | 61 | /* 62 | * Methods 63 | */ 64 | 65 | function postAjax(url, timeout, data, success, error) { 66 | var xhr = new XMLHttpRequest(); 67 | 68 | xhr.onload = function() { 69 | success(xhr.response); 70 | }; 71 | 72 | xhr.onerror = function() { 73 | error(); 74 | }; 75 | 76 | xhr.ontimeout = function() { 77 | error("timeout"); 78 | }; 79 | 80 | xhr.open('POST', url, true); 81 | xhr.responseType = "arraybuffer"; 82 | xhr.timeout = timeout; 83 | xhr.send(new DataView(data)); 84 | 85 | return xhr; 86 | } 87 | 88 | function stopRequests() { 89 | // Set the poll function to a dummy function. 90 | // This will prevent further poll calls. 91 | poll = function() {}; 92 | 93 | // Kill the ajax requests. 94 | if (pollXhr) { 95 | pollXhr.abort(); 96 | } 97 | if (sendXhr) { 98 | sendXhr.abort(); 99 | } 100 | } 101 | 102 | function triggerClosed() { 103 | // Stop the ajax requests. 104 | stopRequests(); 105 | 106 | // Trigger the event. 107 | s.onClose(); 108 | } 109 | 110 | function triggerError(msg) { 111 | // Stop the ajax requests. 112 | stopRequests(); 113 | 114 | // Create the error message. 115 | if (!msg) { 116 | msg = "the ajax socket closed the connection with an error."; 117 | } 118 | 119 | // Trigger the event. 120 | s.onError(msg); 121 | } 122 | 123 | function send(reqType, headerStr, data, callback) { 124 | var b = new ByteBuffer(3, ByteBuffer.BIG_ENDIAN, true); 125 | b.writeByte(reqType); 126 | 127 | var headerStrLen = 0; 128 | if (headerStr && headerStr.length > 0) { 129 | headerStrLen = headerStr.length; 130 | } 131 | b.writeByte(headerStrLen); 132 | 133 | if (headerStrLen > 0) { 134 | b.writeString(headerStr); 135 | } 136 | 137 | if (data && data.byteLength > 0) { 138 | b.write(data); 139 | } 140 | 141 | // Perform the actual ajax request. 142 | sendXhr = postAjax(host, sendTimeout, b.buffer, function (data) { 143 | sendXhr = false; 144 | 145 | if (callback) { 146 | callback(data); 147 | } 148 | }, function (msg) { 149 | sendXhr = false; 150 | triggerError(msg); 151 | }); 152 | } 153 | 154 | poll = function () { 155 | var b = new ByteBuffer(3, ByteBuffer.BIG_ENDIAN, true); 156 | b.writeByte(RequestType.Poll); 157 | 158 | var headerStr = uid + DataDelimiter + pollToken; 159 | b.writeByte(headerStr.length); 160 | b.writeString(headerStr); 161 | 162 | // Perform the actual ajax request. 163 | pollXhr = postAjax(host, pollTimeout, b.buffer, function (data) { 164 | pollXhr = false; 165 | 166 | var b = new ByteBuffer(data, ByteBuffer.BIG_ENDIAN); 167 | 168 | // Extract the tyoe. 169 | if (b.length < 1) { 170 | triggerError("ajax socket: poll: invalid server response"); 171 | return; 172 | } 173 | var type = b.readByte(); 174 | 175 | // Check if this ajax connection was closed. 176 | if (type == PollType.Closed) { 177 | triggerClosed(); 178 | return; 179 | } 180 | 181 | // Validate. 182 | if (b.length < 2) { 183 | triggerError("ajax socket: poll: invalid server response"); 184 | return; 185 | } 186 | 187 | // Extract and set the new poll token. 188 | var pollTokenLen = b.readByte(); 189 | pollToken = b.readString(pollTokenLen); 190 | 191 | // Check if this ajax request has reached the server's timeout. 192 | if (type == PollType.Timeout) { 193 | // Just start the next poll request. 194 | poll(); 195 | return; 196 | } 197 | 198 | // Start the next poll request. 199 | poll(); 200 | 201 | // Remove the header from the buffer. 202 | b.clip(); 203 | 204 | // Call the event. 205 | s.onMessage(b.buffer); 206 | }, function (msg) { 207 | pollXhr = false; 208 | triggerError(msg); 209 | }); 210 | }; 211 | 212 | var push = utils.throttle(function() { 213 | // Skip if there is already an active push request. 214 | // Only one push request at once is allowed. 215 | // The next push will be triggered automatically. 216 | if (pushActive) { 217 | return; 218 | } 219 | 220 | // Obtain the total buffer size. 221 | var i, totalSize = 0; 222 | for (i=0; i < pushBuffer.length; i++) { 223 | totalSize += pushBuffer[i].byteLength; 224 | } 225 | 226 | // Merge all buffered bytes into one single buffer. 227 | var b = new ByteBuffer(totalSize, ByteBuffer.BIG_ENDIAN); 228 | for (i=0; i < pushBuffer.length; i++) { 229 | b.write(pushBuffer[i]); 230 | } 231 | 232 | // Clear the push buffer. 233 | pushBuffer = []; 234 | 235 | // Perform the actual push request. 236 | pushActive = true; 237 | send(RequestType.Push, uid + DataDelimiter + pushToken, b.buffer, function(data) { 238 | pushActive = false; 239 | 240 | if (!data || data.byteLength <= 0) { 241 | triggerError("ajax socket: push: invalid server response"); 242 | return; 243 | } 244 | 245 | var b = new ByteBuffer(data, ByteBuffer.BIG_ENDIAN); 246 | 247 | // Set the new push token. 248 | pushToken = b.readString(); 249 | 250 | // Check if the buffer is filled again. 251 | // If so, trigger the next push. 252 | if (pushBuffer.length > 0) { 253 | push(); 254 | } 255 | }); 256 | }, 50); 257 | 258 | 259 | /* 260 | * Socket layer implementation. 261 | */ 262 | 263 | s.open = function () { 264 | // Initialize the ajax socket session 265 | send(RequestType.Init, null, null, function (data) { 266 | if (!data || data.byteLength <= 0) { 267 | triggerError("ajax socket: open: invalid server response"); 268 | return; 269 | } 270 | 271 | // Transform to string. 272 | var b = new ByteBuffer(data, ByteBuffer.BIG_ENDIAN); 273 | data = b.readString(); 274 | 275 | // Split the string. 276 | var split = data.split(DataDelimiter); 277 | if (split.length !== 3) { 278 | triggerError("ajax socket: failed to obtain uid and tokens"); 279 | return; 280 | } 281 | 282 | // Set the uid and the tokens. 283 | uid = split[0]; 284 | pollToken = split[1]; 285 | pushToken = split[2]; 286 | 287 | // Start the long polling process. 288 | poll(); 289 | 290 | // Trigger the event. 291 | s.onOpen(); 292 | }); 293 | }; 294 | 295 | s.send = function (data) { 296 | // Add the data to the push buffer queue. 297 | pushBuffer.push(data); 298 | 299 | // Push the data to the server (throttled). 300 | push(); 301 | }; 302 | 303 | s.close = function() { 304 | // Stop the ajax requests. 305 | stopRequests(); 306 | }; 307 | 308 | return s; 309 | }; 310 | -------------------------------------------------------------------------------- /client/src/binarysocket.js: -------------------------------------------------------------------------------- 1 | /* 2 | * BinarySocket - Binary Web Sockets 3 | * Copyright (C) 2016 Roland Singer 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | 19 | 20 | var BinarySocket = function() { 21 | // Turn on strict mode. 22 | 'use strict'; 23 | 24 | // Include the dependencies. 25 | @@include('./vendor/byte-buffer.js') 26 | @@include('./utils.js') 27 | @@include('./socket.js') 28 | 29 | // The public BinarySocket instance. 30 | return { 31 | // Open and return a new BinarySocket. 32 | // The first argument is required. It defines a host which has to start with 33 | // http:// or https:// or / for an absolute path using the current host. 34 | // The second argument defines optional options. 35 | open: openSocket, 36 | 37 | // Create a new ByteBuffer. 38 | // Optionally set the implicitGrowth boolean. 39 | // Wrapper for JavaScript's ArrayBuffer/DataView maintaining index and default endianness. 40 | // More information: https://github.com/desertbit/byte-buffer 41 | newByteBuffer: function(data, implicitGrowth) { 42 | return new ByteBuffer(data, ByteBuffer.BIG_ENDIAN, implicitGrowth); 43 | }, 44 | 45 | // Convert an ArrayBuffer to a string. 46 | bytesToString: function(b) { 47 | var bb = this.newByteBuffer(b); 48 | return bb.readString(); 49 | }, 50 | 51 | // Convert a string to an ArrayBuffer. 52 | stringToBytes: function(s) { 53 | var b = this.newByteBuffer(1, true); 54 | b.writeString(s); 55 | return b.buffer; 56 | } 57 | }; 58 | }(); 59 | -------------------------------------------------------------------------------- /client/src/socket.js: -------------------------------------------------------------------------------- 1 | /* 2 | * BinarySocket - Binary Web Sockets 3 | * Copyright (C) 2016 Roland Singer 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | 19 | /* 20 | * This code lives inside the BinarySocket function. 21 | */ 22 | 23 | var openSocket = function(host, options) { 24 | // Include the dependencies. 25 | @@include('./websocket.js') 26 | @@include('./ajaxsocket.js') 27 | 28 | 29 | 30 | /* 31 | * Constants 32 | */ 33 | 34 | var SocketTypes = { 35 | WebSocket: "WebSocket", 36 | AjaxSocket: "AjaxSocket" 37 | }; 38 | 39 | var DefaultOptions = { 40 | // Force a socket type. 41 | // Values: false, "WebSocket", "AjaxSocket" 42 | forceSocketType: false, 43 | 44 | // Kill the connect attempt after the timeout. 45 | connectTimeout: 10000 46 | }; 47 | 48 | 49 | 50 | /* 51 | * Variables 52 | */ 53 | 54 | var bs, // Backend socket. 55 | isClosed = false; 56 | 57 | 58 | 59 | /* 60 | * Public Instance 61 | */ 62 | 63 | var instance = { 64 | // Return the current socket type. 65 | // Values: "WebSocket", "AjaxSocket" 66 | socketType: function() { 67 | return bs.socketType; 68 | }, 69 | 70 | // Close the socket connection. 71 | close: function() { 72 | bs.close(); 73 | triggerClose(); 74 | }, 75 | 76 | // Returns a boolean whenever the socket is closed. 77 | isClosed: function() { 78 | return isClosed; 79 | }, 80 | 81 | // Write the ArrayBuffer to the socket. 82 | write: function(data) { 83 | if (isClosed) { 84 | console.log("BinarySocket: failed to write: the socket is closed"); 85 | return; 86 | } 87 | else if (!(data instanceof ArrayBuffer)) { 88 | console.log("BinarySocket: failed to write data: data is not of type ArrayBuffer"); 89 | return; 90 | } 91 | else if (data.byteLength === 0) { 92 | return; 93 | } 94 | 95 | bs.send(data); 96 | }, 97 | 98 | // Function which is triggered as soon as new bytes are received. 99 | // The passed data is an ArrayBuffer. 100 | onRead: function(data) {} // Set to an empty function. This eliminates an extra check. 101 | 102 | /* 103 | // Hint: Further available event function. 104 | 105 | // Function which is triggered as soon as the connection is established. 106 | onOpen: function() {} 107 | 108 | // Function which is triggered as soon as the connection closes. 109 | onClose: function() {} 110 | 111 | // Function which is triggered as soon as the connection closes with an error. 112 | // An optional error message is passed. 113 | // onClose is also triggered afterwards. 114 | onError: function(msg) {} 115 | */ 116 | }; 117 | 118 | 119 | 120 | /* 121 | * Methods 122 | */ 123 | 124 | function triggerOpen() { 125 | // Trigger only once. 126 | if (bs.openTriggered) { 127 | return; 128 | } 129 | bs.openTriggered = true; 130 | 131 | if (instance.onOpen) { 132 | try { 133 | instance.onOpen(); 134 | } catch (e) { 135 | console.log("BinarySocket: onOpen: catched exception:", e); 136 | 137 | // Ensure to close the socket. 138 | bs.close(); 139 | } 140 | } 141 | } 142 | 143 | function triggerClose() { 144 | // Trigger only once. 145 | if (isClosed) { 146 | return; 147 | } 148 | isClosed = true; 149 | 150 | if (instance.onClose) { 151 | try { 152 | instance.onClose(); 153 | } catch (e) { 154 | console.log("BinarySocket: onClose: catched exception:", e); 155 | } 156 | } 157 | } 158 | 159 | function triggerError(msg) { 160 | // Trigger only once. 161 | if (bs.errorTriggered) { 162 | return; 163 | } 164 | bs.errorTriggered = true; 165 | 166 | if (instance.onError) { 167 | try { 168 | instance.onError(msg); 169 | } catch (e) { 170 | console.log("BinarySocket: onError: catched exception:", e); 171 | } 172 | } 173 | } 174 | 175 | function connectSocket() { 176 | // Choose the socket layer depending on the browser support. 177 | if ((!options.forceSocketType && window.WebSocket) || 178 | options.forceSocketType === SocketTypes.WebSocket) 179 | { 180 | bs = newWebSocket(); 181 | bs.socketType = SocketTypes.WebSocket; 182 | } 183 | else { 184 | bs = newAjaxSocket(); 185 | bs.socketType = SocketTypes.AjaxSocket; 186 | } 187 | 188 | // Start the timeout. 189 | var connectTimeout = setTimeout(function() { 190 | connectTimeout = false; 191 | 192 | // Ensure the socket is closed. 193 | bs.close(); 194 | 195 | triggerError("connection timeout"); 196 | triggerClose(); 197 | }, options.connectTimeout); 198 | 199 | // Helper function. 200 | var stopConnectTimeout = function() { 201 | if (connectTimeout !== false) { 202 | clearTimeout(connectTimeout); 203 | connectTimeout = false; 204 | } 205 | }; 206 | 207 | 208 | 209 | // Set the backend socket events. 210 | bs.onOpen = function() { 211 | stopConnectTimeout(); 212 | 213 | triggerOpen(); 214 | }; 215 | 216 | bs.onClose = function() { 217 | stopConnectTimeout(); 218 | 219 | // Ensure the socket is closed. 220 | bs.close(); 221 | 222 | triggerClose(); 223 | }; 224 | 225 | bs.onError = function(msg) { 226 | // Stop the connect timeout. 227 | stopConnectTimeout(); 228 | 229 | // Ensure the socket is closed. 230 | bs.close(); 231 | 232 | triggerError(msg); 233 | triggerClose(); 234 | }; 235 | 236 | bs.onMessage = function(data) { 237 | try { 238 | instance.onRead(data); 239 | } catch (e) { 240 | console.log("BinarySocket: onRead: catched exception:", e); 241 | } 242 | }; 243 | 244 | // Connect during the next tick. 245 | // The user should be able to connect the event functions first. 246 | setTimeout(function() { 247 | bs.open(); 248 | }, 0); 249 | } 250 | 251 | 252 | 253 | /* 254 | * Initialize section 255 | */ 256 | 257 | // Check if ArrayBuffers are supported. This is a must! 258 | if (!window.ArrayBuffer) { 259 | console.log("BinarySocket: ArrayBuffers are not supported by this browser!"); 260 | return ; 261 | } 262 | 263 | // Merge the options with the default options. 264 | options = utils.extend({}, DefaultOptions, options); 265 | 266 | // Prepare the host string. 267 | // Prepent the current location if the host url starts with a slash. 268 | if (host.match("^/")) { 269 | host = window.location.protocol + "//" + window.location.host + host; 270 | } 271 | // Use the current location if the host string is not set. 272 | else if (!host) { 273 | host = window.location.protocol + "//" + window.location.host; 274 | } 275 | // The host string has to start with http:// or https:// 276 | if (!host.match("^http://") && !host.match("^https://")) { 277 | console.log("BinarySocket: invalid host: missing 'http://' or 'https://'!"); 278 | return; 279 | } 280 | 281 | // Connect the socket. 282 | connectSocket(); 283 | 284 | 285 | // Return the newly created socket. 286 | return instance; 287 | }; 288 | -------------------------------------------------------------------------------- /client/src/utils.js: -------------------------------------------------------------------------------- 1 | /* 2 | * BinarySocket - Binary Web Sockets 3 | * Copyright (C) 2016 Roland Singer 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | 19 | /* 20 | * This code lives inside the BinarySocket function. 21 | */ 22 | 23 | var utils = { 24 | // Mimics jQuery's extend method. 25 | // Source: http://stackoverflow.com/questions/11197247/javascript-equivalent-of-jquerys-extend-method 26 | extend: function() { 27 | for(var i=1; i 4 | * 5 | * Wrapper for JavaScript's ArrayBuffer/DataView. 6 | * 7 | * Licensed under the MIT license. 8 | */ 9 | 10 | !function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.ByteBuffer=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o this.length) { 70 | this._index = this.length; 71 | } 72 | } 73 | }, { 74 | key: '_extractBuffer', 75 | 76 | // Extracts buffer from given source and optionally clones it 77 | value: function _extractBuffer(source) { 78 | var clone = arguments[1] === undefined ? false : arguments[1]; 79 | 80 | // Whether source is a byte-aware object 81 | if (source && typeof source.byteLength !== 'undefined') { 82 | 83 | // Determine whether source is a view or a raw buffer 84 | if (typeof source.buffer !== 'undefined') { 85 | return clone ? source.buffer.slice(0) : source.buffer; 86 | } else { 87 | return clone ? source.slice(0) : source; 88 | } 89 | 90 | // Whether source is a sequence of bytes 91 | } else if (source && typeof source.length !== 'undefined') { 92 | 93 | // Although Uint8Array's constructor succeeds when given strings, 94 | // it does not correctly instantiate the buffer 95 | if (source.constructor == String) { 96 | return null; 97 | } 98 | 99 | try { 100 | return new Uint8Array(source).buffer; 101 | } catch (error) { 102 | return null; 103 | } 104 | 105 | // No buffer found 106 | } else { 107 | return null; 108 | } 109 | } 110 | }, { 111 | key: 'front', 112 | 113 | // Sets index to front of the buffer 114 | value: function front() { 115 | this._index = 0; 116 | return this; 117 | } 118 | }, { 119 | key: 'end', 120 | 121 | // Sets index to end of the buffer 122 | value: function end() { 123 | this._index = this.length; 124 | return this; 125 | } 126 | }, { 127 | key: 'seek', 128 | 129 | // Seeks given number of bytes 130 | // Note: Backwards seeking is supported 131 | value: function seek() { 132 | var bytes = arguments[0] === undefined ? 1 : arguments[0]; 133 | 134 | this.index += bytes; 135 | return this; 136 | } 137 | }, { 138 | key: 'read', 139 | 140 | // Reads sequence of given number of bytes (defaults to number of bytes available) 141 | value: function read() { 142 | var bytes = arguments[0] === undefined ? this.available : arguments[0]; 143 | 144 | if (bytes > this.available) { 145 | throw new Error('Cannot read ' + bytes + ' byte(s), ' + this.available + ' available'); 146 | } 147 | 148 | if (bytes <= 0) { 149 | throw new RangeError('Invalid number of bytes ' + bytes); 150 | } 151 | 152 | var value = new ByteBuffer(this._buffer.slice(this._index, this._index + bytes), this.order); 153 | this._index += bytes; 154 | return value; 155 | } 156 | }, { 157 | key: 'write', 158 | 159 | // Writes sequence of bytes 160 | value: function write(sequence) { 161 | var view; 162 | 163 | // Ensure we're dealing with a Uint8Array view 164 | if (!(sequence instanceof Uint8Array)) { 165 | 166 | // Extract the buffer from the sequence 167 | var buffer = this._extractBuffer(sequence); 168 | if (!buffer) { 169 | throw new TypeError('Cannot write ' + sequence + ', not a sequence'); 170 | } 171 | 172 | // And create a new Uint8Array view for it 173 | view = new Uint8Array(buffer); 174 | } else { 175 | view = sequence; 176 | } 177 | 178 | var available = this.available; 179 | if (view.byteLength > available) { 180 | if (this._implicitGrowth) { 181 | this.append(view.byteLength - available); 182 | } else { 183 | throw new Error('Cannot write ' + sequence + ' using ' + view.byteLength + ' byte(s), ' + this.available + ' available'); 184 | } 185 | } 186 | 187 | this._raw.set(view, this._index); 188 | this._index += view.byteLength; 189 | return this; 190 | } 191 | }, { 192 | key: 'readString', 193 | 194 | // Reads UTF-8 encoded string of given number of bytes (defaults to number of bytes available) 195 | // 196 | // Based on David Flanagan's BufferView (https://github.com/davidflanagan/BufferView/blob/master/BufferView.js//L195) 197 | value: function readString() { 198 | var bytes = arguments[0] === undefined ? this.available : arguments[0]; 199 | 200 | if (bytes > this.available) { 201 | throw new Error('Cannot read ' + bytes + ' byte(s), ' + this.available + ' available'); 202 | } 203 | 204 | if (bytes <= 0) { 205 | throw new RangeError('Invalid number of bytes ' + bytes); 206 | } 207 | 208 | // Local reference 209 | var raw = this._raw; 210 | 211 | // Holds decoded characters 212 | var codepoints = []; 213 | 214 | // Index into codepoints 215 | var c = 0; 216 | 217 | // Bytes 218 | var b1, 219 | b2, 220 | b3, 221 | b4 = null; 222 | 223 | // Target index 224 | var target = this._index + bytes; 225 | 226 | while (this._index < target) { 227 | b1 = raw[this._index]; 228 | 229 | if (b1 < 128) { 230 | // One byte sequence 231 | codepoints[c++] = b1; 232 | this._index++; 233 | } else if (b1 < 194) { 234 | throw new Error('Unexpected continuation byte'); 235 | } else if (b1 < 224) { 236 | // Two byte sequence 237 | b2 = raw[this._index + 1]; 238 | 239 | if (b2 < 128 || b2 > 191) { 240 | throw new Error('Bad continuation byte'); 241 | } 242 | 243 | codepoints[c++] = ((b1 & 31) << 6) + (b2 & 63); 244 | 245 | this._index += 2; 246 | } else if (b1 < 240) { 247 | 248 | // Three byte sequence 249 | b2 = raw[this._index + 1]; 250 | 251 | if (b2 < 128 || b2 > 191) { 252 | throw new Error('Bad continuation byte'); 253 | } 254 | 255 | b3 = raw[this._index + 2]; 256 | 257 | if (b3 < 128 || b3 > 191) { 258 | throw new Error('Bad continuation byte'); 259 | } 260 | 261 | codepoints[c++] = ((b1 & 15) << 12) + ((b2 & 63) << 6) + (b3 & 63); 262 | 263 | this._index += 3; 264 | } else if (b1 < 245) { 265 | // Four byte sequence 266 | b2 = raw[this._index + 1]; 267 | 268 | if (b2 < 128 || b2 > 191) { 269 | throw new Error('Bad continuation byte'); 270 | } 271 | 272 | b3 = raw[this._index + 2]; 273 | 274 | if (b3 < 128 || b3 > 191) { 275 | throw new Error('Bad continuation byte'); 276 | } 277 | 278 | b4 = raw[this._index + 3]; 279 | 280 | if (b4 < 128 || b4 > 191) { 281 | throw new Error('Bad continuation byte'); 282 | } 283 | 284 | var cp = ((b1 & 7) << 18) + ((b2 & 63) << 12) + ((b3 & 63) << 6) + (b4 & 63); 285 | cp -= 65536; 286 | 287 | // Turn code point into two surrogate pairs 288 | codepoints[c++] = 55296 + ((cp & 1047552) >>> 10); 289 | codepoints[c++] = 56320 + (cp & 1023); 290 | 291 | this._index += 4; 292 | } else { 293 | throw new Error('Illegal byte'); 294 | } 295 | } 296 | 297 | // Browsers may have hardcoded or implicit limits on the array length when applying a function 298 | // See: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/apply//apply_and_built-in_functions 299 | var limit = 1 << 16; 300 | var length = codepoints.length; 301 | if (length < limit) { 302 | return String.fromCharCode.apply(String, codepoints); 303 | } else { 304 | var chars = []; 305 | var i = 0; 306 | while (i < length) { 307 | chars.push(String.fromCharCode.apply(String, codepoints.slice(i, i + limit))); 308 | i += limit; 309 | } 310 | return chars.join(''); 311 | } 312 | } 313 | }, { 314 | key: 'writeString', 315 | 316 | // Writes UTF-8 encoded string 317 | // Note: Does not write string length or terminator 318 | // 319 | // Based on David Flanagan's BufferView (https://github.com/davidflanagan/BufferView/blob/master/BufferView.js//L264) 320 | value: function writeString(string) { 321 | 322 | // Encoded UTF-8 bytes 323 | var bytes = []; 324 | 325 | // String length, offset and byte offset 326 | var length = string.length; 327 | var i = 0; 328 | var b = 0; 329 | 330 | while (i < length) { 331 | var c = string.charCodeAt(i); 332 | 333 | if (c <= 127) { 334 | // One byte sequence 335 | bytes[b++] = c; 336 | } else if (c <= 2047) { 337 | // Two byte sequence 338 | bytes[b++] = 192 | (c & 1984) >>> 6; 339 | bytes[b++] = 128 | c & 63; 340 | } else if (c <= 55295 || c >= 57344 && c <= 65535) { 341 | // Three byte sequence 342 | // Source character is not a UTF-16 surrogate 343 | bytes[b++] = 224 | (c & 61440) >>> 12; 344 | bytes[b++] = 128 | (c & 4032) >>> 6; 345 | bytes[b++] = 128 | c & 63; 346 | } else { 347 | // Four byte sequence 348 | if (i == length - 1) { 349 | throw new Error('Unpaired surrogate ' + string[i] + ' (index ' + i + ')'); 350 | } 351 | 352 | // Retrieve surrogate 353 | var d = string.charCodeAt(++i); 354 | if (c < 55296 || c > 56319 || d < 56320 || d > 57343) { 355 | throw new Error('Unpaired surrogate ' + string[i] + ' (index ' + i + ')'); 356 | } 357 | 358 | var cp = ((c & 1023) << 10) + (d & 1023) + 65536; 359 | 360 | bytes[b++] = 240 | (cp & 1835008) >>> 18; 361 | bytes[b++] = 128 | (cp & 258048) >>> 12; 362 | bytes[b++] = 128 | (cp & 4032) >>> 6; 363 | bytes[b++] = 128 | cp & 63; 364 | } 365 | 366 | ++i; 367 | } 368 | 369 | this.write(bytes); 370 | 371 | return bytes.length; 372 | } 373 | }, { 374 | key: 'readCString', 375 | 376 | // Aliases for reading/writing UTF-8 encoded strings 377 | // readUTFChars: this.::readString 378 | // writeUTFChars: this.::writeString 379 | 380 | // Reads UTF-8 encoded C-string (excluding the actual NULL-byte) 381 | value: function readCString() { 382 | var bytes = this._raw; 383 | var length = bytes.length; 384 | var i = this._index; 385 | while (bytes[i] != 0 && i < length) { 386 | ++i; 387 | } 388 | 389 | length = i - this._index; 390 | if (length > 0) { 391 | var string = this.readString(length); 392 | this.readByte(); 393 | return string; 394 | } 395 | 396 | return null; 397 | } 398 | }, { 399 | key: 'writeCString', 400 | 401 | // Writes UTF-8 encoded C-string (NULL-terminated) 402 | value: function writeCString(string) { 403 | var bytes = this.writeString(string); 404 | this.writeByte(0); 405 | return ++bytes; 406 | } 407 | }, { 408 | key: 'prepend', 409 | 410 | // Prepends given number of bytes 411 | value: function prepend(bytes) { 412 | if (bytes <= 0) { 413 | throw new RangeError('Invalid number of bytes ' + bytes); 414 | } 415 | 416 | var view = new Uint8Array(this.length + bytes); 417 | view.set(this._raw, bytes); 418 | this._index += bytes; 419 | this.buffer = view.buffer; 420 | return this; 421 | } 422 | }, { 423 | key: 'append', 424 | 425 | // Appends given number of bytes 426 | value: function append(bytes) { 427 | if (bytes <= 0) { 428 | throw new RangeError('Invalid number of bytes ' + bytes); 429 | } 430 | 431 | var view = new Uint8Array(this.length + bytes); 432 | view.set(this._raw, 0); 433 | this.buffer = view.buffer; 434 | return this; 435 | } 436 | }, { 437 | key: 'clip', 438 | 439 | // Clips this buffer 440 | value: function clip() { 441 | var begin = arguments[0] === undefined ? this._index : arguments[0]; 442 | var end = arguments[1] === undefined ? this.length : arguments[1]; 443 | 444 | if (begin < 0) { 445 | begin = this.length + begin; 446 | } 447 | var buffer = this._buffer.slice(begin, end); 448 | this._index -= begin; 449 | this.buffer = buffer; 450 | return this; 451 | } 452 | }, { 453 | key: 'slice', 454 | 455 | // Slices this buffer 456 | value: function slice() { 457 | var begin = arguments[0] === undefined ? 0 : arguments[0]; 458 | var end = arguments[1] === undefined ? this.length : arguments[1]; 459 | 460 | var slice = new ByteBuffer(this._buffer.slice(begin, end), this.order); 461 | return slice; 462 | } 463 | }, { 464 | key: 'clone', 465 | 466 | // Clones this buffer 467 | value: function clone() { 468 | var clone = new ByteBuffer(this._buffer.slice(0), this.order, this.implicitGrowth); 469 | clone.index = this._index; 470 | return clone; 471 | } 472 | }, { 473 | key: 'reverse', 474 | 475 | // Reverses this buffer 476 | value: function reverse() { 477 | Array.prototype.reverse.call(this._raw); 478 | this._index = 0; 479 | return this; 480 | } 481 | }, { 482 | key: 'toArray', 483 | 484 | // Array of bytes in this buffer 485 | value: function toArray() { 486 | return Array.prototype.slice.call(this._raw, 0); 487 | } 488 | }, { 489 | key: 'toString', 490 | 491 | // Short string representation of this buffer 492 | value: function toString() { 493 | var order = this._order == this.constructor.BIG_ENDIAN ? 'big-endian' : 'little-endian'; 494 | return '[ByteBuffer; Order: ' + order + '; Length: ' + this.length + '; Index: ' + this._index + '; Available: ' + this.available + ']'; 495 | } 496 | }, { 497 | key: 'toHex', 498 | 499 | // Hex representation of this buffer with given spacer 500 | value: function toHex() { 501 | var spacer = arguments[0] === undefined ? ' ' : arguments[0]; 502 | 503 | return Array.prototype.map.call(this._raw, function (byte) { 504 | return ('00' + byte.toString(16).toUpperCase()).slice(-2); 505 | }).join(spacer); 506 | } 507 | }, { 508 | key: 'toASCII', 509 | 510 | // ASCII representation of this buffer with given spacer and optional byte alignment 511 | value: function toASCII() { 512 | var spacer = arguments[0] === undefined ? ' ' : arguments[0]; 513 | var align = arguments[1] === undefined ? true : arguments[1]; 514 | var unknown = arguments[2] === undefined ? '�' : arguments[2]; 515 | 516 | var prefix = align ? ' ' : ''; 517 | return Array.prototype.map.call(this._raw, function (byte) { 518 | return byte < 32 || byte > 126 ? prefix + unknown : prefix + String.fromCharCode(byte); 519 | }).join(spacer); 520 | } 521 | }, { 522 | key: 'buffer', 523 | 524 | // Retrieves buffer 525 | get: function () { 526 | return this._buffer; 527 | }, 528 | 529 | // Sets new buffer and sanitizes read/write index 530 | set: function (buffer) { 531 | this._buffer = buffer; 532 | this._raw = new Uint8Array(this._buffer); 533 | this._view = new DataView(this._buffer); 534 | this._sanitizeIndex(); 535 | } 536 | }, { 537 | key: 'raw', 538 | 539 | // Retrieves raw buffer 540 | get: function () { 541 | return this._raw; 542 | } 543 | }, { 544 | key: 'view', 545 | 546 | // Retrieves view 547 | get: function () { 548 | return this._view; 549 | } 550 | }, { 551 | key: 'length', 552 | 553 | // Retrieves number of bytes 554 | get: function () { 555 | return this._buffer.byteLength; 556 | } 557 | }, { 558 | key: 'byteLength', 559 | 560 | // Retrieves number of bytes 561 | // Note: This allows for ByteBuffer to be detected as a proper source by its own constructor 562 | get: function () { 563 | return this.length; 564 | } 565 | }, { 566 | key: 'order', 567 | 568 | // Retrieves byte order 569 | get: function () { 570 | return this._order; 571 | }, 572 | 573 | // Sets byte order 574 | set: function (order) { 575 | this._order = !!order; 576 | } 577 | }, { 578 | key: 'implicitGrowth', 579 | 580 | // Retrieves implicit growth strategy 581 | get: function () { 582 | return this._implicitGrowth; 583 | }, 584 | 585 | // Sets implicit growth strategy 586 | set: function (implicitGrowth) { 587 | this._implicitGrowth = !!implicitGrowth; 588 | } 589 | }, { 590 | key: 'index', 591 | 592 | // Retrieves read/write index 593 | get: function () { 594 | return this._index; 595 | }, 596 | 597 | // Sets read/write index 598 | set: function (index) { 599 | if (index < 0 || index > this.length) { 600 | throw new RangeError('Invalid index ' + index + ', should be between 0 and ' + this.length); 601 | } 602 | 603 | this._index = index; 604 | } 605 | }, { 606 | key: 'available', 607 | 608 | // Retrieves number of available bytes 609 | get: function () { 610 | return this.length - this._index; 611 | } 612 | }], [{ 613 | key: 'LITTLE_ENDIAN', 614 | 615 | // Byte order constants 616 | value: true, 617 | enumerable: true 618 | }, { 619 | key: 'BIG_ENDIAN', 620 | value: false, 621 | enumerable: true 622 | }]); 623 | 624 | return ByteBuffer; 625 | })(); 626 | 627 | // Generic reader 628 | var reader = function reader(method, bytes) { 629 | return function () { 630 | var order = arguments[0] === undefined ? this._order : arguments[0]; 631 | 632 | if (bytes > this.available) { 633 | throw new Error('Cannot read ' + bytes + ' byte(s), ' + this.available + ' available'); 634 | } 635 | 636 | var value = this._view[method](this._index, order); 637 | this._index += bytes; 638 | return value; 639 | }; 640 | }; 641 | 642 | // Generic writer 643 | var writer = function writer(method, bytes) { 644 | return function (value) { 645 | var order = arguments[1] === undefined ? this._order : arguments[1]; 646 | 647 | var available = this.available; 648 | if (bytes > available) { 649 | if (this._implicitGrowth) { 650 | this.append(bytes - available); 651 | } else { 652 | throw new Error('Cannot write ' + value + ' using ' + bytes + ' byte(s), ' + available + ' available'); 653 | } 654 | } 655 | 656 | this._view[method](this._index, value, order); 657 | this._index += bytes; 658 | return this; 659 | }; 660 | }; 661 | 662 | // Readers for bytes, shorts, integers, floats and doubles 663 | ByteBuffer.prototype.readByte = reader('getInt8', 1); 664 | ByteBuffer.prototype.readUnsignedByte = reader('getUint8', 1); 665 | ByteBuffer.prototype.readShort = reader('getInt16', 2); 666 | ByteBuffer.prototype.readUnsignedShort = reader('getUint16', 2); 667 | ByteBuffer.prototype.readInt = reader('getInt32', 4); 668 | ByteBuffer.prototype.readUnsignedInt = reader('getUint32', 4); 669 | ByteBuffer.prototype.readFloat = reader('getFloat32', 4); 670 | ByteBuffer.prototype.readDouble = reader('getFloat64', 8); 671 | 672 | // Writers for bytes, shorts, integers, floats and doubles 673 | ByteBuffer.prototype.writeByte = writer('setInt8', 1); 674 | ByteBuffer.prototype.writeUnsignedByte = writer('setUint8', 1); 675 | ByteBuffer.prototype.writeShort = writer('setInt16', 2); 676 | ByteBuffer.prototype.writeUnsignedShort = writer('setUint16', 2); 677 | ByteBuffer.prototype.writeInt = writer('setInt32', 4); 678 | ByteBuffer.prototype.writeUnsignedInt = writer('setUint32', 4); 679 | ByteBuffer.prototype.writeFloat = writer('setFloat32', 4); 680 | ByteBuffer.prototype.writeDouble = writer('setFloat64', 8); 681 | 682 | module.exports = ByteBuffer; 683 | },{}]},{},[1]) 684 | (1) 685 | }); 686 | -------------------------------------------------------------------------------- /client/src/websocket.js: -------------------------------------------------------------------------------- 1 | /* 2 | * BinarySocket - Binary Web Sockets 3 | * Copyright (C) 2016 Roland Singer 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | 19 | /* 20 | * This code lives inside the BinarySocket function. 21 | */ 22 | 23 | var newWebSocket = function () { 24 | /* 25 | * Variables 26 | */ 27 | 28 | var s = {}, 29 | ws; 30 | 31 | 32 | 33 | /* 34 | * Socket layer implementation. 35 | */ 36 | 37 | s.open = function () { 38 | try { 39 | // Generate the websocket url. 40 | var url; 41 | if (host.match("^https://")) { 42 | url = "wss" + host.substr(5); 43 | } else { 44 | url = "ws" + host.substr(4); 45 | } 46 | 47 | // Open the websocket connection 48 | ws = new WebSocket(url); 49 | ws.binaryType = 'arraybuffer'; 50 | 51 | // Set the callback handlers 52 | ws.onmessage = function(event) { 53 | s.onMessage(event.data); 54 | }; 55 | 56 | ws.onerror = function(event) { 57 | var msg = "the websocket closed the connection with "; 58 | if (event.code) { 59 | msg += "the error code: " + event.code; 60 | } 61 | else { 62 | msg += "an error."; 63 | } 64 | 65 | s.onError(msg); 66 | }; 67 | 68 | ws.onclose = function() { 69 | s.onClose(); 70 | }; 71 | 72 | ws.onopen = function() { 73 | s.onOpen(); 74 | }; 75 | } catch (e) { 76 | s.onError(); 77 | } 78 | }; 79 | 80 | s.send = function (data) { 81 | // Send the data to the server 82 | ws.send(data); 83 | }; 84 | 85 | s.close = function() { 86 | // Close the websocket if defined. 87 | if (ws) { 88 | try { 89 | ws.close(); 90 | } catch (e) {} 91 | } 92 | 93 | ws = undefined; 94 | }; 95 | 96 | return s; 97 | }; 98 | -------------------------------------------------------------------------------- /neterror.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BinarySocket - Binary Web Sockets 3 | * Copyright (C) 2016 Roland Singer 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | 19 | package binarysocket 20 | 21 | //#####################// 22 | //### netError Type ###// 23 | //#####################// 24 | 25 | // netError satisfies the net Error interface. 26 | type netError struct { 27 | msg string 28 | temporary bool 29 | timeout bool 30 | } 31 | 32 | func (e *netError) Error() string { return e.msg } 33 | func (e *netError) Temporary() bool { return e.temporary } 34 | func (e *netError) Timeout() bool { return e.timeout } 35 | -------------------------------------------------------------------------------- /options.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BinarySocket - Binary Web Sockets 3 | * Copyright (C) 2016 Roland Singer 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | 19 | package binarysocket 20 | 21 | import "net/http" 22 | 23 | //#################// 24 | //### Constants ###// 25 | //#################// 26 | 27 | const ( 28 | defaultReadBufferSize = 4096 29 | defaultWriteBufferSize = 4096 30 | ) 31 | 32 | //####################// 33 | //### Options Type ###// 34 | //####################// 35 | 36 | // Options define the BinarySocket optional options. 37 | type Options struct { 38 | // ReadBufferSize and WriteBufferSize specify I/O buffer sizes. If a buffer 39 | // size is zero, then a default value of 4096 is used. The I/O buffer sizes 40 | // do not limit the size of the messages that can be sent or received. 41 | ReadBufferSize, WriteBufferSize int 42 | 43 | // CheckOrigin returns true if the request Origin header is acceptable. If 44 | // CheckOrigin is nil, the host in the Origin header must not be set or 45 | // must match the host of the request. 46 | // This method is used by the backend sockets before establishing connections. 47 | CheckOrigin func(r *http.Request) bool 48 | 49 | // DisableAjax deactivates the ajax backend. 50 | DisableAjax bool 51 | } 52 | 53 | func (o *Options) setDefaults() { 54 | if o.ReadBufferSize <= 0 { 55 | o.ReadBufferSize = defaultReadBufferSize 56 | } 57 | if o.WriteBufferSize <= 0 { 58 | o.WriteBufferSize = defaultWriteBufferSize 59 | } 60 | if o.CheckOrigin == nil { 61 | o.CheckOrigin = checkSameOrigin 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /options_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BinarySocket - Binary Web Sockets 3 | * Copyright (C) 2016 Roland Singer 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | 19 | package binarysocket 20 | 21 | import ( 22 | "testing" 23 | 24 | "github.com/stretchr/testify/require" 25 | ) 26 | 27 | func TestOptionsSetDefaults(t *testing.T) { 28 | o := new(Options) 29 | o.setDefaults() 30 | require.Equal(t, defaultReadBufferSize, o.ReadBufferSize) 31 | require.Equal(t, defaultWriteBufferSize, o.WriteBufferSize) 32 | require.NotNil(t, o.CheckOrigin) 33 | require.False(t, o.DisableAjax) 34 | 35 | o.ReadBufferSize = 1 36 | o.WriteBufferSize = 1 37 | o.DisableAjax = true 38 | o.setDefaults() 39 | require.Equal(t, 1, o.ReadBufferSize) 40 | require.Equal(t, 1, o.WriteBufferSize) 41 | require.True(t, o.DisableAjax) 42 | } 43 | -------------------------------------------------------------------------------- /sample/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | BinarySocket 6 | 7 | 8 | 9 |

BinarySocket Sample

10 | 11 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /sample/sample.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BinarySocket - Binary Web Sockets 3 | * Copyright (C) 2016 Roland Singer 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | 19 | package main 20 | 21 | import ( 22 | "bufio" 23 | "log" 24 | "net" 25 | "net/http" 26 | 27 | "github.com/desertbit/binarysocket" 28 | ) 29 | 30 | var ( 31 | server *binarysocket.Server 32 | ) 33 | 34 | func main() { 35 | // Create a new binarysocket web server. 36 | server = binarysocket.NewServer() 37 | 38 | // Start a new goroutine accepting new sockets. 39 | go acceptSockets() 40 | 41 | // Set the binarysocket server handler. 42 | http.Handle("/binsocket", server) 43 | 44 | // Set the http file server. 45 | http.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir("public")))) 46 | http.Handle("/dist/", http.StripPrefix("/dist/", http.FileServer(http.Dir("../client/dist")))) 47 | 48 | // Start the http server. 49 | err := http.ListenAndServe(":8888", nil) 50 | if err != nil { 51 | log.Fatalf("ListenAndServe: %v", err) 52 | } 53 | } 54 | 55 | func acceptSockets() { 56 | // Accept all sockets. 57 | for { 58 | conn, err := server.Accept() 59 | if err != nil { 60 | log.Println(err) 61 | 62 | if err == binarysocket.ErrClosed { 63 | return 64 | } 65 | 66 | continue 67 | } 68 | 69 | go handleSocket(conn) 70 | } 71 | } 72 | 73 | func handleSocket(conn net.Conn) { 74 | log.Println("new socket connected") 75 | 76 | // Just read line by line. 77 | r := bufio.NewReader(conn) 78 | 79 | line, err := r.ReadString('\n') 80 | for err == nil { 81 | log.Print("received from client: ", line) 82 | 83 | // Echo back to the client. 84 | _, err = conn.Write([]byte(line)) 85 | if err != nil { 86 | log.Fatalf("socket write error: %v", err) 87 | } 88 | 89 | // Read the next line. 90 | line, err = r.ReadString('\n') 91 | } 92 | 93 | if err != nil { 94 | log.Printf("socket read: %v", err) 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /utils.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BinarySocket - Binary Web Sockets 3 | * Copyright (C) 2016 Roland Singer 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | 19 | package binarysocket 20 | 21 | import ( 22 | "crypto/rand" 23 | "net" 24 | "net/http" 25 | "net/url" 26 | "strings" 27 | 28 | "github.com/sirupsen/logrus" 29 | ) 30 | 31 | var ( 32 | // Log is the public logrus value used internally. 33 | Log = logrus.New() 34 | ) 35 | 36 | //###############// 37 | //### Private ###// 38 | //###############// 39 | 40 | // httpErrLog writes the HTTP status code and logs the error. 41 | func httpErrLog(w http.ResponseWriter, r *http.Request, statusCode int, err error) { 42 | // Set the HTTP status code. 43 | w.WriteHeader(statusCode) 44 | 45 | // Get the remote address and user agent. 46 | remoteAddr, _ := extractRemoteAddress(r) 47 | userAgent := r.Header.Get("User-Agent") 48 | 49 | // Log the invalid request. 50 | Log.WithFields(logrus.Fields{ 51 | "remoteAddress": remoteAddr, 52 | "userAgent": userAgent, 53 | "url": r.URL.Path, 54 | }).Warningf("handle HTTP request: %v", err) 55 | } 56 | 57 | // extractRemoteAddress returns the IP address of the request. 58 | // If the X-Forwarded-For or X-Real-Ip http headers are set, then 59 | // they are used to obtain the remote address. 60 | // The boolean is true, if the remote address is obtained using the 61 | // request's RemoteAddr() method. 62 | // A "IP:port" string is returned. 63 | func extractRemoteAddress(r *http.Request) (string, bool) { 64 | // Split the host and port of the remote address. 65 | _, port, err := net.SplitHostPort(r.RemoteAddr) 66 | if err != nil { 67 | // Just return the remote address if an error occurrs. 68 | return r.RemoteAddr, true 69 | } 70 | 71 | // The request header. 72 | hdr := r.Header 73 | 74 | // Try to obtain the ip from the X-Forwarded-For header 75 | ip := hdr.Get("X-Forwarded-For") 76 | if len(ip) > 0 { 77 | // X-Forwarded-For is potentially a list of addresses separated with "," 78 | parts := strings.Split(ip, ",") 79 | if len(parts) > 0 { 80 | ip = strings.TrimSpace(parts[0]) 81 | 82 | if len(ip) > 0 { 83 | return ip + ":" + port, false 84 | } 85 | } 86 | } 87 | 88 | // Try to obtain the ip from the X-Real-Ip header 89 | ip = strings.TrimSpace(hdr.Get("X-Real-Ip")) 90 | if len(ip) > 0 { 91 | return ip + ":" + port, false 92 | } 93 | 94 | // Fallback to the request remote address 95 | return r.RemoteAddr, true 96 | } 97 | 98 | // checkSameOrigin returns true if the origin is not set or is equal to the request host. 99 | // Source from gorilla websockets. 100 | func checkSameOrigin(r *http.Request) bool { 101 | origin := r.Header["Origin"] 102 | if len(origin) == 0 { 103 | return true 104 | } 105 | u, err := url.Parse(origin[0]) 106 | if err != nil { 107 | return false 108 | } 109 | return u.Host == r.Host 110 | } 111 | 112 | // randomString generates a random string. 113 | func randomString(n int) (string, error) { 114 | const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" 115 | var bytes = make([]byte, n) 116 | _, err := rand.Read(bytes) 117 | if err != nil { 118 | return "", err 119 | } 120 | for i, b := range bytes { 121 | bytes[i] = alphanum[b%byte(len(alphanum))] 122 | } 123 | return string(bytes), nil 124 | } 125 | -------------------------------------------------------------------------------- /utils_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BinarySocket - Binary Web Sockets 3 | * Copyright (C) 2016 Roland Singer 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | 19 | package binarysocket 20 | 21 | import ( 22 | "net/http" 23 | "testing" 24 | 25 | "github.com/stretchr/testify/require" 26 | ) 27 | 28 | func TestExtractRemoteAddress(t *testing.T) { 29 | r, err := http.NewRequest("GET", "http://127.0.0.1", nil) 30 | require.NoError(t, err) 31 | 32 | r.RemoteAddr = "127.0.0.1:8888" 33 | s, b := extractRemoteAddress(r) 34 | require.Equal(t, "127.0.0.1:8888", s) 35 | require.True(t, b) 36 | 37 | r.Header.Add("X-Forwarded-For", " 1.1.1.1 ") 38 | s, b = extractRemoteAddress(r) 39 | require.Equal(t, "1.1.1.1:8888", s) 40 | require.False(t, b) 41 | 42 | r.Header.Del("X-Forwarded-For") 43 | r.Header.Add("X-Forwarded-For", " 1.1.1.1 , 2.2.2.2 , 3.3.3.3 ") 44 | s, b = extractRemoteAddress(r) 45 | require.Equal(t, "1.1.1.1:8888", s) 46 | require.False(t, b) 47 | 48 | r.Header.Del("X-Forwarded-For") 49 | r.Header.Add("X-Real-Ip", " 4.4.4.4 ") 50 | s, b = extractRemoteAddress(r) 51 | require.Equal(t, "4.4.4.4:8888", s) 52 | require.False(t, b) 53 | } 54 | -------------------------------------------------------------------------------- /websocket.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BinarySocket - Binary Web Sockets 3 | * Copyright (C) 2016 Roland Singer 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | 19 | package binarysocket 20 | 21 | import ( 22 | "fmt" 23 | "io" 24 | "net" 25 | "net/http" 26 | "time" 27 | 28 | "github.com/gorilla/websocket" 29 | ) 30 | 31 | //###################// 32 | //### wsConn Type ###// 33 | //###################// 34 | 35 | type wsConn struct { 36 | ws *websocket.Conn 37 | reader io.Reader 38 | remoteAddr net.Addr 39 | } 40 | 41 | func (c *wsConn) Read(data []byte) (n int, err error) { 42 | // Only retry once. Check the EOF comment down. 43 | Loop: 44 | for i := 0; i <= 1; i++ { 45 | // Obtain the next reader from the websocket if nil. 46 | if c.reader == nil { 47 | _, c.reader, err = c.ws.NextReader() 48 | if err != nil { 49 | return 0, transformWebSocketError(err) 50 | } 51 | } 52 | 53 | // Read from the websocket. 54 | n, err = c.reader.Read(data) 55 | if err != nil { 56 | // Reset the reader if EOF is reached. 57 | // This will get the next reader during the next read. 58 | if err == io.EOF { 59 | c.reader = nil 60 | 61 | // If 0, EOF is returned, then immediately obtain the next reader and 62 | // retry once. Quote from package io: 63 | // An instance of this general case is that a Reader returning a non-zero 64 | // number of bytes at the end of the input stream may return either 65 | // err == EOF or err == nil. The next Read should return 0, EOF. 66 | if n == 0 { 67 | continue Loop 68 | } 69 | 70 | return n, nil 71 | } 72 | 73 | return n, transformWebSocketError(err) 74 | } 75 | 76 | return n, nil 77 | } 78 | 79 | return 0, nil 80 | } 81 | 82 | func (c *wsConn) Write(data []byte) (n int, err error) { 83 | err = c.ws.WriteMessage(websocket.BinaryMessage, data) 84 | if err != nil { 85 | return 0, transformWebSocketError(err) 86 | } 87 | 88 | return len(data), nil 89 | } 90 | 91 | func (c *wsConn) Close() error { 92 | return c.ws.Close() 93 | } 94 | 95 | func (c *wsConn) LocalAddr() net.Addr { 96 | return c.ws.LocalAddr() 97 | } 98 | 99 | func (c *wsConn) RemoteAddr() net.Addr { 100 | return c.remoteAddr 101 | } 102 | 103 | func (c *wsConn) SetDeadline(t time.Time) error { 104 | err := c.SetReadDeadline(t) 105 | if err != nil { 106 | return err 107 | } 108 | 109 | return c.SetWriteDeadline(t) 110 | } 111 | 112 | func (c *wsConn) SetReadDeadline(t time.Time) error { 113 | return c.ws.SetReadDeadline(t) 114 | } 115 | 116 | func (c *wsConn) SetWriteDeadline(t time.Time) error { 117 | return c.ws.SetWriteDeadline(t) 118 | } 119 | 120 | //###############// 121 | //### Private ###// 122 | //###############// 123 | 124 | func (s *Server) handleWebSocketRequest(rw http.ResponseWriter, req *http.Request) { 125 | // Upgrade to a websocket. 126 | ws, err := s.upgrader.Upgrade(rw, req, nil) 127 | if err != nil { 128 | httpErrLog(rw, req, http.StatusBadRequest, fmt.Errorf("websocket: failed to upgrade to websocket layer: %v", err)) 129 | return 130 | } 131 | // Create a new websocket connection instance. 132 | wsc := &wsConn{ 133 | ws: ws, 134 | } 135 | 136 | // If special http headers are set to extract the real remote address, then use it. 137 | remoteAddrStr, requestRemoteAddrMethodUsed := extractRemoteAddress(req) 138 | if requestRemoteAddrMethodUsed { 139 | wsc.remoteAddr = ws.RemoteAddr() 140 | } else { 141 | wsc.remoteAddr = &addr{ 142 | network: ws.RemoteAddr().Network(), 143 | str: remoteAddrStr, 144 | } 145 | } 146 | 147 | // Finally handle over the new connection to the server. 148 | s.onNewSocketConn(wsc) 149 | } 150 | 151 | func transformWebSocketError(err error) error { 152 | // Websocket close code. 153 | wsCode := -1 // -1 for not set. 154 | 155 | // Try to obtain the websocket close code if present. 156 | // Assert to gorilla websocket CloseError type if possible. 157 | if closeErr, ok := err.(*websocket.CloseError); ok { 158 | wsCode = closeErr.Code 159 | } 160 | 161 | // Return the custom error if the websocket is closed. 162 | if wsCode == websocket.CloseNormalClosure || 163 | wsCode == websocket.CloseGoingAway || 164 | wsCode == websocket.CloseNoStatusReceived { 165 | return ErrClosed 166 | } 167 | 168 | return err 169 | } 170 | --------------------------------------------------------------------------------