├── .gitignore ├── .travis.yml ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── pom.xml ├── src └── com │ └── blogspot │ └── debukkitsblog │ ├── crypt │ ├── CryptedObject.java │ ├── Crypter.java │ └── DHKeyFactory.java │ └── net │ ├── Client.java │ ├── Datapackage.java │ ├── Executable.java │ └── Server.java └── ssc.store /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | /bin/ 3 | *.class 4 | 5 | # Log file 6 | *.log 7 | 8 | # BlueJ files 9 | *.ctxt 10 | 11 | # Mobile Tools for Java (J2ME) 12 | .mtj.tmp/ 13 | 14 | # Package Files # 15 | *.jar 16 | *.war 17 | *.ear 18 | *.zip 19 | *.tar.gz 20 | *.rar 21 | 22 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 23 | hs_err_pid* 24 | 25 | # Eclipse IDE 26 | .project 27 | .classpath 28 | .settings 29 | *.jardesc 30 | 31 | # Test files 32 | src/StartSSCTest.java 33 | src/TestClient.java 34 | src/TestServer.java 35 | 36 | # Maven Binaries 37 | /target/ 38 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guidelines 2 | 3 | ## Code Style 4 | - Do not use a single line for a {, but put it at the end of the previous line 5 | - Do not leave { or } out even if this is possible, e.g. when writing an if statement with just one line in its body 6 | - Do not change the line breaks of the Javadoc 7 | 8 | ## Java Version 9 | - Only use language features that are possible in Java 8 or earlier. 10 | 11 | 12 | Thank you for contributing! -------------------------------------------------------------------------------- /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 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 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 | {project} Copyright (C) {year} {fullname} 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 | ### SimpleServerClient ### 2 | 3 | A very lightweight and easy-to-use library for client-server-client or simply server-client applications in Java doing all the work for you: connection setup, reconnection, timeout, keep-alive etc. in the background. Simply tell the application what to send and receive, and the rest will happen by itself. That's almost magic! 4 | 5 | **Code Quality and Build Status** 6 | 7 | [![Build Status](https://travis-ci.org/DeBukkIt/SimpleServerClient.svg?branch=master)](https://travis-ci.org/DeBukkIt/SimpleServerClient) 8 | 9 | # How to use THE SERVER 10 | ```java 11 | import java.net.Socket; 12 | 13 | public class MyServer extends Server { 14 | 15 | public MyServer(int port) { 16 | super(port); 17 | } 18 | 19 | @Override 20 | public void preStart() { 21 | registerMethod("SOME_MESSAGE", new Executable() { 22 | @Override 23 | public void run(Datapackage msg, Socket socket) { 24 | doSomethingWith(msg); 25 | sendReply(socket, "Hey, thanks for your message. Greetings!") 26 | } 27 | }); 28 | } 29 | 30 | } 31 | ``` 32 | 33 | Just make your own class, e. g. MyServer extending Server, simply use the original constructor and implement 34 | the preStart() method. In the preStart method just add 35 | ```java 36 | registerMethod("IDENTIFIER", new Executable() { 37 | @Override 38 | public void run(Datapackage msg, Socket socket) { 39 | doSomethingWith(msg, socket); 40 | sendReply(socket, "Some Reply"); 41 | } 42 | }); 43 | ``` 44 | for every identifier of an Datapackge the server received, you want to react to. 45 | 46 | EXAMPLE: So if you register "Ping" and an Executable responding "Pong" to the client, just register 47 | ```java 48 | registerMethod("PING", new Executable() { 49 | @Override 50 | public void run(Datapackage msg, Socket socket) { 51 | sendReply(socket, "Pong"); 52 | } 53 | }); 54 | ``` 55 | and that's it. 56 | 57 | For more identifiers to react on, just put those lines multiple times into your preStart(). Do not forget to send 58 | a reply to the clients you got the Datapackge from, because they will wait until the world ends for a response from you. 59 | 60 | EXAMPLE for a server broadcasting a chat-message to all connected clients: 61 | ```java 62 | registerMethod("Message", new Executable() { 63 | @Override 64 | public void run(Datapackage msg, Socket socket) { 65 | System.out.println("[Message] New chat message arrived, delivering to all the clients..."); 66 | broadcastMessage(msg); //The broadcast to all the receivers 67 | sendReply(socket, String.valueOf(reveicerCount)); //The reply (NECESSARY! unless you want the client to block while waiting for this package) 68 | } 69 | }); 70 | ``` 71 | 72 | 73 | # How to use THE CLIENT 74 | ```java 75 | import java.net.Socket; 76 | 77 | public class MyClient extends Client { 78 | 79 | public MyClient(String id, String address, int port) { 80 | super(id, address, port); 81 | 82 | registerMethod("SOME_MESSAGE", new Executable() { 83 | @Override 84 | public void run(Datapackage msg, Socket socket) { 85 | System.out.println("Look! I got a new message from the server: " + msg.get(1)); 86 | } 87 | }); 88 | 89 | start(); // Do not forget to start the client! 90 | } 91 | 92 | } 93 | ``` 94 | 95 | 96 | 97 | Just make your own class, e. g. MyClient extending Client, simply use the original constructor. Whenever you are ready for the client to login, call start(). The client will connect to the server depending on the constructor-parameters and register itself on the server. From now on it can receive messages from the server and stay connected (and reconnects if necessary) until you call stop(). 98 | 99 | 100 | To react on an incoming message, just add 101 | ```java 102 | registerMethod("IDENTIFIER", new Executable() { 103 | @Override 104 | public void run(Datapackage msg, Socket socket) { 105 | doSomethingWith(msg, socket); 106 | } 107 | }); 108 | ``` 109 | somewhere, I suggest the constructor itself, for every message ID you want to handle. 110 | 111 | 112 | EXMAPLE for an incoming chat message from the server: 113 | ```java 114 | registerMethod("PING", new Executable() { 115 | @Override 116 | public void run(Datapackage msg, Socket socket) { 117 | System.out.println("Look! I got a new message from the server: " + msg.get(1)); 118 | // msg.get(1); should now return "Pong" in our example. 119 | } 120 | }); 121 | ``` 122 | 123 | Different from the client, the server will not expect a reply by default. So dont always send him an Reply-Package, because he 124 | needs an extra-identifier-method registered for that. 125 | 126 | 127 | # Useful methods 128 | AS SERVER: 129 | - Broadcast messages using: broadcastMessage(...) 130 | - Use IDs and group names to register your clients to the server. This allows you to decide what clients or groups of clients may receive a particular broadcast. 131 | - Send messages to a specified client using: sendMessage(...) 132 | - Receive messages from the client using registerMethod-Executables 133 | 134 | AS CLIENT: 135 | - Send messages to the server using: sendMessage(...) 136 | - Receive replys to this message using its return value (that will be reply Datapackage) 137 | - Receive messages from the server using registerMethod-Executables at any time 138 | 139 | # Event handlers 140 | There a some event handlers (e.g. onConnectionGood(), onConnectionProblem(), onClientRegistered(...), etc.) you can overwrite to handle these events. 141 | 142 | # Custom message processing 143 | The client and server classes both provide the onLog and onLogError event handlers, which can be overridden in the implementation if the info messages and error messages should not (only) be output in the console. 144 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | com.blogspot.debukkitsblog 4 | SimpleServerClient 5 | 2.4.1 6 | SimpleServerClient 7 | A very lightweight and easy-to-use library for client-server-client or simply server-client applications in Java doing all the work for you: connection setup, reconnection, timeout, keep-alive etc. in the background. Simply tell the application what to send and receive, and the rest will happen by itself. That's almost magic! 8 | 9 | UTF-8 10 | 11 | 12 | src 13 | 14 | 15 | src 16 | 21 | 22 | 23 | 24 | 25 | maven-compiler-plugin 26 | 3.7.0 27 | 28 | 1.8 29 | 1.8 30 | 31 | 32 | 33 | 34 | https://github.com/DeBukkIt/SimpleServerClient 35 | 36 | -------------------------------------------------------------------------------- /src/com/blogspot/debukkitsblog/crypt/CryptedObject.java: -------------------------------------------------------------------------------- 1 | package com.blogspot.debukkitsblog.crypt; 2 | 3 | import java.io.Serializable; 4 | 5 | /** 6 | * A CryptedObject stores the encrypted data generated using the Crypter utility 7 | * 8 | * @author Leonard Bienbeck 9 | * @version 2.3.0 10 | */ 11 | public class CryptedObject implements Serializable { 12 | 13 | /** 14 | * 15 | */ 16 | private static final long serialVersionUID = -5575861158027167628L; 17 | 18 | private byte[] bytes; 19 | 20 | /** 21 | * Constructs a CryptedObject by taking an array of bytes and storing it 22 | * 23 | * @param bytes The array of bytes to be stored 24 | */ 25 | public CryptedObject(byte[] bytes) { 26 | this.bytes = bytes; 27 | } 28 | 29 | /** 30 | * Returns the bytes stored in the CryptedObject 31 | * 32 | * @return The bytes stored in the CryptedObject 33 | */ 34 | public byte[] getBytes() { 35 | return bytes; 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/com/blogspot/debukkitsblog/crypt/Crypter.java: -------------------------------------------------------------------------------- 1 | package com.blogspot.debukkitsblog.crypt; 2 | 3 | import java.io.ByteArrayInputStream; 4 | import java.io.ByteArrayOutputStream; 5 | import java.io.ObjectInput; 6 | import java.io.ObjectInputStream; 7 | import java.io.ObjectOutput; 8 | import java.io.ObjectOutputStream; 9 | import java.nio.charset.Charset; 10 | import java.security.Key; 11 | import javax.crypto.Cipher; 12 | import javax.crypto.spec.SecretKeySpec; 13 | 14 | /** 15 | * Provides methods to encrypt and decrypt Objects 16 | * 17 | * @author Leonard Bienbeck 18 | */ 19 | public class Crypter { 20 | 21 | private static final String ALGO = "AES"; 22 | 23 | /** 24 | * Encrypts an Object and returns its encrypted equivalent CryptedObject 25 | * 26 | * @param o The object to encrypt 27 | * @param password The password to use for encryption 28 | * @return The CryptedObject equivalent of the given object 29 | */ 30 | public static CryptedObject encrypt(Object o, String password) { 31 | try { 32 | ByteArrayOutputStream bos = new ByteArrayOutputStream(); 33 | ObjectOutput out = new ObjectOutputStream(bos); 34 | out.writeObject(o); 35 | return new CryptedObject(encrypt(bos.toByteArray(), password)); 36 | } catch (Exception e) { 37 | e.printStackTrace(); 38 | return null; 39 | } 40 | } 41 | 42 | /** 43 | * Decrypts a CryptedObject using a password and returns its decrypted equivalent Object 44 | * 45 | * @param co The CryptedObject to decrypt 46 | * @param password The password to use for decryption 47 | * @return The decrypted object 48 | * @throws DecryptionFailedException If decryption fails. A wrong password will cause this. 49 | */ 50 | public static Object decrypt(CryptedObject co, String password) throws DecryptionFailedException { 51 | try { 52 | ByteArrayInputStream bis = new ByteArrayInputStream(decrypt(co.getBytes(), password)); 53 | ObjectInput in = new ObjectInputStream(bis); 54 | return in.readObject(); 55 | } catch (Exception e) { 56 | throw new DecryptionFailedException(); 57 | } 58 | } 59 | 60 | /** 61 | * Encrypts an array of bytes using the AES algorithm 62 | * 63 | * @param data The array of bytes to encrypt 64 | * @param rawKey The password to use for encryption. Warning: This password will be extended or 65 | * shortened to match a length of 16 bytes (128 bit). Therefore be careful! Different 66 | * passwords, starting with the same sixteen characters, result in the same AES key. 67 | * @return An array of bytes containing the encrypted data 68 | * @throws Exception If something went wrong with the AES algorithm. 69 | */ 70 | public static byte[] encrypt(byte[] data, String rawKey) throws Exception { 71 | Key key = generateKey(rawKey); 72 | Cipher c = Cipher.getInstance(ALGO); 73 | c.init(Cipher.ENCRYPT_MODE, key); 74 | byte[] encVal = c.doFinal(data); 75 | return encVal; 76 | } 77 | 78 | /** 79 | * Decrypts an array of bytes using the AES algorithm 80 | * 81 | * @param encryptedData The array of bytes to decrtypt 82 | * @param rawKey The password to use for decryption. Warning: This password will be extended or 83 | * shortened to match a length of 16 bytes (128 bit). Therefore be careful! Different 84 | * passwords, starting with the same sixteen characters, result in the same AES key. 85 | * @return An array of bytes containing the decrypted data 86 | * @throws Exception If something went wrong. This might happen when the password is wrong. 87 | */ 88 | public static byte[] decrypt(byte[] encryptedData, String rawKey) throws Exception { 89 | Key key = generateKey(rawKey); 90 | Cipher c = Cipher.getInstance(ALGO); 91 | c.init(Cipher.DECRYPT_MODE, key); 92 | byte[] decValue = c.doFinal(encryptedData); 93 | return decValue; 94 | } 95 | 96 | /** 97 | * Generates a key to use with the AES algorithm using a String key.
98 | * Warning: This key will be extended or shortened to match a length of 16 bytes (128 bit). 99 | * Therefore be careful! Different passwords, starting with the same sixteen characters, result in 100 | * the same AES key. 101 | * 102 | * @param key A String of 128 bit (16 characters) 103 | * @return An AES compatible Key object used by the encrypter to encrypt the data 104 | * @throws Exception If something went wrong with the AES algorithm. 105 | */ 106 | private static Key generateKey(String key) throws Exception { 107 | String resultKey = key; 108 | while (resultKey.length() < 32) { 109 | resultKey += resultKey; 110 | } 111 | resultKey = resultKey.substring(0, 32); 112 | 113 | byte[] keyValue = resultKey.getBytes(Charset.forName("UTF-8")); 114 | return new SecretKeySpec(keyValue, ALGO); 115 | } 116 | 117 | /** 118 | * The exception thrown when a decryption fails.
119 | * This might happen if the password is wrong. 120 | */ 121 | public static class DecryptionFailedException extends Exception { 122 | 123 | /** 124 | * 125 | */ 126 | private static final long serialVersionUID = 5911192741823907010L; 127 | 128 | @Override 129 | public String getMessage() { 130 | return "Decryption failed. Is the password correct?"; 131 | } 132 | } 133 | 134 | } 135 | -------------------------------------------------------------------------------- /src/com/blogspot/debukkitsblog/crypt/DHKeyFactory.java: -------------------------------------------------------------------------------- 1 | package com.blogspot.debukkitsblog.crypt; 2 | 3 | import java.math.BigInteger; 4 | import java.util.Random; 5 | 6 | public class DHKeyFactory { 7 | 8 | private BigInteger p, g, s, M, R, K; 9 | 10 | public DHKeyFactory() { 11 | System.out.println("[DHKey] Generating secure key..."); 12 | p = new BigInteger(2048, 12, new Random()); 13 | g = new BigInteger(String.valueOf(4 - new Random().nextInt(3))); 14 | do { 15 | s = new BigInteger(160, new Random()); 16 | } while (s.compareTo(new BigInteger("2")) == -1 17 | || s.compareTo(p.subtract(new BigInteger("1"))) == 0); 18 | } 19 | 20 | public DHKeyFactory(BigInteger p, BigInteger g) { 21 | System.out.println("[DHKey] Generating secure key..."); 22 | this.p = p; 23 | this.g = g; 24 | do { 25 | s = new BigInteger(160, new Random()); 26 | } while (s.compareTo(new BigInteger("2")) == -1 27 | || s.compareTo(p.subtract(new BigInteger("1"))) == 0); 28 | } 29 | 30 | public void overwriteSecret(BigInteger s) { 31 | this.s = s; 32 | } 33 | 34 | public BigInteger getPrime() { 35 | return p; 36 | } 37 | 38 | public BigInteger getGenerator() { 39 | return g; 40 | } 41 | 42 | public BigInteger getPublicKey() { 43 | if (M == null) { 44 | M = g.modPow(s, p); 45 | } 46 | return M; 47 | } 48 | 49 | public void setRemotePublicKey(BigInteger r) { 50 | this.R = r; 51 | } 52 | 53 | public BigInteger getFinalKey() { 54 | if (K == null) { 55 | K = R.modPow(s, p); 56 | } 57 | 58 | return K; 59 | } 60 | 61 | } 62 | -------------------------------------------------------------------------------- /src/com/blogspot/debukkitsblog/net/Client.java: -------------------------------------------------------------------------------- 1 | package com.blogspot.debukkitsblog.net; 2 | 3 | import java.io.BufferedInputStream; 4 | import java.io.BufferedOutputStream; 5 | import java.io.EOFException; 6 | import java.io.IOException; 7 | import java.io.ObjectInputStream; 8 | import java.io.ObjectOutputStream; 9 | import java.net.ConnectException; 10 | import java.net.InetSocketAddress; 11 | import java.net.Socket; 12 | import java.net.SocketException; 13 | import java.nio.channels.AlreadyConnectedException; 14 | import java.util.HashMap; 15 | import java.util.UUID; 16 | import javax.net.ssl.SSLSocketFactory; 17 | 18 | /** 19 | * A very simple Client class for Java network applications
20 | * originally created on March 9, 2016 in Horstmar, Germany 21 | * 22 | * @author Leonard Bienbeck 23 | * @version 2.4.1 24 | */ 25 | public class Client { 26 | 27 | protected String id; 28 | protected String group; 29 | 30 | protected Socket loginSocket; 31 | protected InetSocketAddress address; 32 | protected int timeout; 33 | 34 | protected Thread listeningThread; 35 | protected HashMap idMethods = new HashMap(); 36 | 37 | protected int errorCount; 38 | 39 | protected boolean secureMode; 40 | protected boolean muted; 41 | protected boolean stopped; 42 | 43 | /** 44 | * The default user id Datapackes are signed with. This is a type 4 pseudo randomly generated 45 | * UUID. 46 | */ 47 | public static final String DEFAULT_USER_ID = UUID.randomUUID().toString(); 48 | /** 49 | * The default group id Datapackages are signed with: _DEFAULT_GROUP_ 50 | */ 51 | public static final String DEFAULT_GROUP_ID = "_DEFAULT_GROUP_"; 52 | 53 | /** 54 | * Constructs a simple client with just a hostname and port to connect to 55 | * 56 | * @param hostname The hostname to connect to 57 | * @param port The port to connect to 58 | */ 59 | public Client(String hostname, int port) { 60 | this(hostname, port, 10000, false, DEFAULT_USER_ID, DEFAULT_GROUP_ID); 61 | } 62 | 63 | public Client(String hostname, int port, int timeout) { 64 | this(hostname, port, timeout, false, DEFAULT_USER_ID, DEFAULT_GROUP_ID); 65 | } 66 | 67 | /** 68 | * Constructs a simple client with a hostname and port to connect to and an id the server uses to 69 | * identify this client in the future (e.g. for sending messages only this client should receive) 70 | * 71 | * @param hostname The hostname to connect to 72 | * @param port The port to connect to 73 | * @param id The id the server may use to identify this client 74 | */ 75 | public Client(String hostname, int port, String id) { 76 | this(hostname, port, 10000, false, id, DEFAULT_GROUP_ID); 77 | } 78 | 79 | /** 80 | * Constructs a simple client with a hostname and port to connect to, an id the server uses to 81 | * identify this client in the future (e.g. for sending messages only this client should receive) 82 | * and a group name the server uses to identify this and some other clients in the future (e.g. 83 | * for sending messages to the members of this group, but no other clients) 84 | * 85 | * @param hostname The hostname to connect to 86 | * @param port The port to connect to 87 | * @param id The id the server may use to identify this client 88 | * @param group The group name the server may use to identify this and similar clients 89 | */ 90 | public Client(String hostname, int port, String id, String group) { 91 | this(hostname, port, 10000, false, id, group); 92 | } 93 | 94 | /** 95 | * Constructs a simple client with all possible configurations 96 | * 97 | * @param hostname The hostname to connect to 98 | * @param port The port to connect to 99 | * @param timeout The timeout after a connection attempt will be given up 100 | * @param useSSL Whether a secure SSL connection should be used 101 | * @param id The id the server may use to identify this client 102 | * @param group The group name the server may use to identify this and similar clients 103 | */ 104 | public Client(String hostname, int port, int timeout, boolean useSSL, String id, String group) { 105 | this.id = id; 106 | this.group = group; 107 | 108 | this.errorCount = 0; 109 | this.address = new InetSocketAddress(hostname, port); 110 | this.timeout = timeout; 111 | 112 | this.secureMode = useSSL; 113 | if (secureMode) { 114 | System.setProperty("javax.net.ssl.trustStore", "ssc.store"); 115 | System.setProperty("javax.net.ssl.keyStorePassword", "SimpleServerClient"); 116 | } 117 | } 118 | 119 | /** 120 | * Checks whether the client is connected to the server and waiting for incoming messages. 121 | * 122 | * @return true, if the client is connected to the server and waiting for incoming messages 123 | */ 124 | public boolean isListening() { 125 | return isConnected() && listeningThread != null && listeningThread.isAlive() && errorCount == 0; 126 | } 127 | 128 | /** 129 | * Checks whether the persistent connection to the server listening for incoming messages is 130 | * connected. This does not check whether the client actually waits for incoming messages with the 131 | * help of the listening thread, but only the pure connection to the server. 132 | * 133 | * @return true, if connected 134 | */ 135 | public boolean isConnected() { 136 | return loginSocket != null && loginSocket.isConnected(); 137 | } 138 | 139 | /** 140 | * Checks the connectivity to the server 141 | * 142 | * @return true, if the server can be reached at all using the given address data 143 | */ 144 | public boolean isServerReachable() { 145 | try { 146 | Socket tempSocket = new Socket(); 147 | tempSocket.connect(this.address); 148 | tempSocket.isConnected(); 149 | tempSocket.close(); 150 | return true; 151 | } catch (IOException e) { 152 | return false; 153 | } 154 | } 155 | 156 | /** 157 | * Mutes the console output of this instance, stack traces will still be printed.
158 | * Be careful: This will not prevent processing of messages passed to the onLog and 159 | * onLogError methods, if they were overwritten. 160 | * 161 | * @param muted true if there should be no console output 162 | */ 163 | public void setMuted(boolean muted) { 164 | this.muted = muted; 165 | } 166 | 167 | /** 168 | * Starts the client. This will cause a connection attempt, a login on the server and the start of 169 | * a new listening thread (both to receive messages and broadcasts from the server) 170 | */ 171 | public void start() { 172 | stopped = false; 173 | login(); 174 | startListening(); 175 | } 176 | 177 | /** 178 | * Stops the client. The connection to the server is interrupted as soon as possible and then no 179 | * further Datapackages are received. Warning: The whole process of stopping can take as 180 | * long as the server needs to the next Datapackage, which will wake up the Client and cause him 181 | * to stop. 182 | */ 183 | public void stop() { 184 | stopped = true; 185 | onLog("[Client] Stopping..."); 186 | } 187 | 188 | /** 189 | * Called to repair the connection if it is lost 190 | */ 191 | protected void repairConnection() { 192 | onLog("[Client] [Connection-Repair] Repairing connection..."); 193 | if (loginSocket != null) { 194 | try { 195 | loginSocket.close(); 196 | } catch (IOException e) { 197 | // This exception does not need to result in any further action or output 198 | } 199 | loginSocket = null; 200 | } 201 | 202 | login(); 203 | startListening(); 204 | } 205 | 206 | /** 207 | * Logs in to the server to receive messages and broadcasts from the server later 208 | */ 209 | protected void login() { 210 | if (stopped) { 211 | return; 212 | } 213 | 214 | // 1. connect 215 | try { 216 | onLog("[Client] Connecting" + (secureMode ? " using SSL..." : "...")); 217 | if (loginSocket != null && loginSocket.isConnected()) { 218 | throw new AlreadyConnectedException(); 219 | } 220 | 221 | if (secureMode) { 222 | loginSocket = 223 | SSLSocketFactory.getDefault().createSocket(address.getAddress(), address.getPort()); 224 | } else { 225 | loginSocket = new Socket(); 226 | loginSocket.connect(this.address, this.timeout); 227 | } 228 | 229 | onLog("[Client] Connected to " + loginSocket.getRemoteSocketAddress()); 230 | 231 | // 2. login 232 | try { 233 | onLog("[Client] Logging in..."); 234 | // open an outputstream 235 | ObjectOutputStream out = 236 | new ObjectOutputStream(new BufferedOutputStream(loginSocket.getOutputStream())); 237 | // create a magic login package 238 | Datapackage loginPackage = new Datapackage("_INTERNAL_LOGIN_", id, group); 239 | loginPackage.sign(id, group); 240 | // send the package to the server 241 | out.writeObject(loginPackage); 242 | out.flush(); 243 | // note: this special method does not expect the server to send a reply 244 | onLog("[Client] Logged in."); 245 | onReconnect(); 246 | } catch (IOException ex) { 247 | onLogError("[Client] Login failed."); 248 | } 249 | 250 | } catch (ConnectException e) { 251 | onLogError("[Client] Connection failed: " + e.getMessage()); 252 | onConnectionProblem(); 253 | } catch (IOException e) { 254 | e.printStackTrace(); 255 | onConnectionProblem(); 256 | } 257 | } 258 | 259 | /** 260 | * Starts a new thread listening for messages from the server. A message will only be processed if 261 | * a handler for its identifier has been registered before using 262 | * registerMethod(String identifier, Executable executable) 263 | */ 264 | protected void startListening() { 265 | 266 | // do not restart the listening thread if it is already running 267 | if (listeningThread != null && listeningThread.isAlive()) { 268 | return; 269 | } 270 | 271 | listeningThread = new Thread(new Runnable() { 272 | @Override 273 | public void run() { 274 | 275 | // always repeat if not stopped 276 | while (!stopped) { 277 | try { 278 | // repait connection if something went wrong with the connection 279 | if (loginSocket != null && !loginSocket.isConnected()) { 280 | while (!loginSocket.isConnected()) { 281 | repairConnection(); 282 | if (loginSocket.isConnected()) { 283 | break; 284 | } 285 | 286 | Thread.sleep(5000); 287 | repairConnection(); 288 | } 289 | } 290 | 291 | onConnectionGood(); 292 | 293 | // wait for incoming messages and read them 294 | ObjectInputStream ois = 295 | new ObjectInputStream(new BufferedInputStream(loginSocket.getInputStream())); 296 | Object raw = ois.readObject(); 297 | 298 | // if the client has been stopped while this thread was listening to an arriving 299 | // Datapackage, stop the proccess at this point 300 | if (stopped) { 301 | return; 302 | } 303 | 304 | if (raw instanceof Datapackage) { 305 | final Datapackage msg = (Datapackage) raw; 306 | 307 | // inspect all registered methods 308 | for (final String current : idMethods.keySet()) { 309 | // if the identifier of a method equals the identifier of the Datapackage... 310 | if (current.equalsIgnoreCase(msg.id())) { 311 | onLog("[Client] Message received. Executing method for '" + msg.id() + "'..."); 312 | // execute the registered Executable on a new thread 313 | new Thread(new Runnable() { 314 | @Override 315 | public void run() { 316 | idMethods.get(current).run(msg, loginSocket); 317 | } 318 | }).start(); 319 | break; 320 | } 321 | } 322 | 323 | } 324 | 325 | } catch (SocketException e) { 326 | onConnectionProblem(); 327 | onLogError("[Client] Connection lost"); 328 | repairConnection(); 329 | } catch (ClassNotFoundException | IOException | InterruptedException ex) { 330 | ex.printStackTrace(); 331 | onConnectionProblem(); 332 | onLogError("[Client] Error: The connection to the server is currently interrupted!"); 333 | repairConnection(); 334 | } 335 | 336 | // reset errorCount if no errors occured until this point 337 | errorCount = 0; 338 | 339 | } // while not stopped 340 | 341 | } // run 342 | }); 343 | 344 | // start the thread 345 | listeningThread.start(); 346 | } 347 | 348 | /** 349 | * Sends a message to the server using a brand new socket and returns the server's response 350 | * 351 | * @param message The message to send to the server 352 | * @param timeout The timeout after a connection attempt will be given up 353 | * @return The server's response. The identifier of this Datapackage should be "REPLY" by default, 354 | * the rest is custom data. 355 | */ 356 | public Datapackage sendMessage(Datapackage message, int timeout) { 357 | try { 358 | // connect to the target client's socket 359 | Socket tempSocket; 360 | if (secureMode) { 361 | tempSocket = 362 | SSLSocketFactory.getDefault().createSocket(address.getAddress(), address.getPort()); 363 | } else { 364 | tempSocket = new Socket(); 365 | tempSocket.connect(address, timeout); 366 | } 367 | 368 | // Open output stream and write message 369 | ObjectOutputStream tempOOS = 370 | new ObjectOutputStream(new BufferedOutputStream(tempSocket.getOutputStream())); 371 | message.sign(id, group); 372 | tempOOS.writeObject(message); 373 | tempOOS.flush(); 374 | 375 | // open input stream and wait for server's response. Warning: If the server 376 | // won't send an answer, this lines might block the program or throw an 377 | // EOFException 378 | ObjectInputStream tempOIS = 379 | new ObjectInputStream(new BufferedInputStream(tempSocket.getInputStream())); 380 | Object raw = tempOIS.readObject(); 381 | 382 | // close all streams and the socket 383 | tempOOS.close(); 384 | tempOIS.close(); 385 | tempSocket.close(); 386 | 387 | // return the server's reply if it is a Datapackage 388 | if (raw instanceof Datapackage) { 389 | return (Datapackage) raw; 390 | } 391 | } catch (EOFException ex) { 392 | onLogError( 393 | "[Client] Error right after sending message: EOFException (did the server forget to send a reply?)"); 394 | } catch (IOException | ClassNotFoundException ex) { 395 | onLogError("[Client] Error while sending message"); 396 | ex.printStackTrace(); 397 | } 398 | 399 | return null; 400 | } 401 | 402 | /** 403 | * Sends a message to the server using a brand new socket and returns the server's response 404 | * 405 | * @param ID The ID of the message, allowing the server to decide what to do with its content 406 | * @param content The content of the message 407 | * @return The server's response. The identifier of this Datapackage should be "REPLY" by default, 408 | * the rest is custom data. 409 | */ 410 | public Datapackage sendMessage(String ID, Object... content) { 411 | return sendMessage(new Datapackage(ID, content)); 412 | } 413 | 414 | /** 415 | * Sends a message to the server using a brand new socket and returns the server's response 416 | * 417 | * @param message The message to send to the server 418 | * @return The server's response. The identifier of this Datapackage should be "REPLY" by default, 419 | * the rest is custom data. 420 | */ 421 | public Datapackage sendMessage(Datapackage message) { 422 | return sendMessage(message, this.timeout); 423 | } 424 | 425 | /** 426 | * Registers a method that will be executed if a message containing identifier is received 427 | * 428 | * @param identifier The ID of the message to proccess 429 | * @param executable The method to be called when a message with identifier is received 430 | */ 431 | public void registerMethod(String identifier, Executable executable) { 432 | idMethods.put(identifier, executable); 433 | } 434 | 435 | /** 436 | * Called on the listener's main thread when there is a problem with the connection. Overwrite 437 | * this method when extending this class. 438 | */ 439 | public void onConnectionProblem() { 440 | // Overwrite this method when extending this class 441 | } 442 | 443 | /** 444 | * Called on the listener's main thread when there is no problem with the connection and 445 | * everything is fine. Overwrite this method when extending this class. 446 | */ 447 | public void onConnectionGood() { 448 | // Overwrite this method when extending this class 449 | } 450 | 451 | /** 452 | * Called on the listener's main thread when the client logs in to the server. This happens on the 453 | * first and every further login (e.g. after a re-established connection). Overwrite this method 454 | * when extending this class. 455 | */ 456 | public void onReconnect() { 457 | // Overwrite this method when extending this class 458 | } 459 | 460 | /** 461 | * By default, this method is called whenever an output is to be made. If this method is not 462 | * overwritten, the output is passed to the system's default output stream (if output is not 463 | * muted).
464 | * Error messages are passed to the onLogError event listener.
465 | * Override this method to catch and process the message in a custom way. 466 | * 467 | * @param message The content of the output to be made 468 | */ 469 | public void onLog(String message) { 470 | if (!muted) { 471 | System.out.println(message); 472 | } 473 | } 474 | 475 | /** 476 | * By default, this method is called whenever an error output is to be made. If this method is not 477 | * overwritten, the output is passed to the system's default error output stream (if output is not 478 | * muted).
479 | * Non-error messages are passed to the onLog event listener.
480 | * Override this method to catch and process the message in a custom way. 481 | * 482 | * @param message The content of the error output to be made 483 | */ 484 | public void onLogError(String message) { 485 | if (!muted) { 486 | System.err.println(message); 487 | } 488 | } 489 | 490 | } 491 | -------------------------------------------------------------------------------- /src/com/blogspot/debukkitsblog/net/Datapackage.java: -------------------------------------------------------------------------------- 1 | package com.blogspot.debukkitsblog.net; 2 | 3 | import java.util.ArrayList; 4 | 5 | /** 6 | * A Datapackage contains the data transmitted and received by SimpleServerClient Clients and 7 | * Servers 8 | * 9 | * @author Leonard Bienbeck 10 | * @version 2.4.1 11 | */ 12 | public class Datapackage extends ArrayList { 13 | 14 | /** 15 | * 16 | */ 17 | private static final long serialVersionUID = 8501296964229015349L; 18 | 19 | private String senderID = "UNSIGNED"; 20 | private String senderGroupName = "UNSIGNED"; 21 | 22 | /** 23 | * Constructs a Datapackage consisting of an ID used by the remote application to identify the 24 | * package and payload data 25 | * 26 | * @param id The ID used by the remote application to identify the package 27 | * @param o The payload 28 | */ 29 | public Datapackage(String id, Object... o) { 30 | this.add(0, id); 31 | for (Object current : o) { 32 | this.add(current); 33 | } 34 | } 35 | 36 | /** 37 | * Returns the ID of the package. The Datapackage can be identified with this. 38 | * 39 | * @return The ID of the package 40 | */ 41 | public String id() { 42 | if (!(this.get(0) instanceof String)) { 43 | throw new IllegalArgumentException("Identifier of Datapackage is not a String"); 44 | } 45 | return (String) this.get(0); 46 | } 47 | 48 | /** 49 | * Returns the ID of the sender of this Datapackage. This makes answering easier. 50 | * 51 | * @return The ID of the sender of this Datapackage or UNSIGNED if the Datapackage was not signed 52 | * by the sender 53 | */ 54 | public String getSenderID() { 55 | return this.senderID; 56 | } 57 | 58 | /** 59 | * Returns the name of the group the sender of this Datapackage is member of. This makes answering 60 | * easier. 61 | * 62 | * @return The name of the group the sender of this Datapackage is member of or UNSIGNED if the 63 | * Datapackage was not signed by the sender 64 | */ 65 | public String getSenderGroup() { 66 | return this.senderGroupName; 67 | } 68 | 69 | /** 70 | * Signs the Datapackage with the given ID. This method should only be called internally by the 71 | * sender. Do not call this method unless you know what you do.
72 | * With this information, the receiver will know the source of every incoming Datapackage. This is 73 | * useful to send responses if you don't want to use sendReply. 74 | * 75 | * @param senderID The ID of the sender 76 | * @param senderGroup The name of the group the sender is member of 77 | */ 78 | protected void sign(String senderID, String senderGroup) { 79 | this.senderID = senderID; 80 | this.senderGroupName = senderGroup; 81 | } 82 | 83 | /** 84 | * Returns the Datapackage as ArrayList, containing the Datapackage's ID at index 0 and the 85 | * payload from index 1 to the end. This method is redundant since Datapackage extends ArrayList. 86 | * 87 | * @return The Datapackage itself. 88 | */ 89 | @Deprecated 90 | public ArrayList open() { 91 | return this; 92 | } 93 | 94 | } 95 | -------------------------------------------------------------------------------- /src/com/blogspot/debukkitsblog/net/Executable.java: -------------------------------------------------------------------------------- 1 | package com.blogspot.debukkitsblog.net; 2 | 3 | import java.net.Socket; 4 | 5 | /** 6 | * A functional interface implemented by Client and Server for handling 7 | * incoming Datapackages with specified identifiers. 8 | * 9 | * @author Leonard Bienbeck 10 | * @version 2.4.1 11 | */ 12 | public interface Executable { 13 | 14 | /** 15 | * Implement this method using 16 | * registerMethod(String identifier, Executable executable) of a Server 17 | * or Client to handle incoming Datapackages. Server only: If you send a reply 18 | * to a client from an implementation of this method, use 19 | * sendReply(Socket toSocket, Object... datapackageContent). 20 | * 21 | * @param pack The Datapackage received 22 | * @param socket The Socket you received the Datapackage from 23 | */ 24 | public abstract void run(Datapackage pack, Socket socket); 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/com/blogspot/debukkitsblog/net/Server.java: -------------------------------------------------------------------------------- 1 | package com.blogspot.debukkitsblog.net; 2 | 3 | import java.io.BufferedInputStream; 4 | import java.io.BufferedOutputStream; 5 | import java.io.IOException; 6 | import java.io.ObjectInputStream; 7 | import java.io.ObjectOutputStream; 8 | import java.net.ConnectException; 9 | import java.net.ServerSocket; 10 | import java.net.Socket; 11 | import java.net.SocketException; 12 | import java.nio.channels.IllegalBlockingModeException; 13 | import java.util.ArrayList; 14 | import java.util.HashMap; 15 | import java.util.UUID; 16 | import javax.net.ssl.SSLServerSocketFactory; 17 | 18 | /** 19 | * A very simple-to-use Server class for Java network applications
20 | * originally created on March 9, 2016 in Horstmar, Germany 21 | * 22 | * @author Leonard Bienbeck 23 | * @version 2.4.2 24 | */ 25 | public abstract class Server { 26 | 27 | protected HashMap idMethods = new HashMap(); 28 | 29 | protected ServerSocket server; 30 | protected int port; 31 | protected ArrayList clients; 32 | protected ArrayList toBeDeleted; 33 | 34 | protected Thread listeningThread; 35 | 36 | protected boolean autoRegisterEveryClient; 37 | protected boolean secureMode; 38 | 39 | protected boolean stopped; 40 | protected boolean muted; 41 | protected long pingInterval = 30 * 1000; // 30 seconds 42 | 43 | protected static final String INTERNAL_LOGIN_ID = "_INTERNAL_LOGIN_"; 44 | 45 | /** 46 | * Constructs a simple server listening on the given port. Every client that connects to this 47 | * server is registered and can receive broadcast and direct messages, the connection will be kept 48 | * alive using a ping and ssl will not be used. This constructor is deprecated! It is strongly 49 | * recommended to substitute it with the constructor that has the option muted as its last 50 | * parameter. 51 | * 52 | * @param port The port to listen on 53 | */ 54 | @Deprecated 55 | public Server(int port) { 56 | this(port, true, true, false); 57 | } 58 | 59 | /** 60 | * Constructs a simple server listening on the given port. Every client that connects to this 61 | * server is registered and can receive broadcast and direct messages, the connection will be kept 62 | * alive using a ping and ssl will not be used. 63 | * 64 | * @param port The port to listen on 65 | * @param muted Whether the mute mode should be activated on startup 66 | */ 67 | public Server(int port, boolean muted) { 68 | this(port, true, true, false, muted); 69 | } 70 | 71 | /** 72 | * Constructs a simple server with all possible configurations. This constructor is deprecated! 73 | * It is strongly recommended to substitute it with the constructor that has the option 74 | * muted as its last parameter. 75 | * 76 | * @param port The port to listen on 77 | * @param autoRegisterEveryClient Whether a client that connects should be registered to send it 78 | * broadcast and direct messages later 79 | * @param keepConnectionAlive Whether the connection should be kept alive using a ping package. 80 | * The transmission interval can be set using setPingInterval(int seconds). 81 | * @param useSSL Whether SSL should be used to establish a secure connection 82 | */ 83 | @Deprecated 84 | public Server(int port, boolean autoRegisterEveryClient, boolean keepConnectionAlive, 85 | boolean useSSL) { 86 | this.clients = new ArrayList(); 87 | this.port = port; 88 | this.autoRegisterEveryClient = autoRegisterEveryClient; 89 | this.muted = false; 90 | 91 | this.secureMode = useSSL; 92 | if (secureMode) { 93 | System.setProperty("javax.net.ssl.keyStore", "ssc.store"); 94 | System.setProperty("javax.net.ssl.keyStorePassword", "SimpleServerClient"); 95 | } 96 | if (autoRegisterEveryClient) { 97 | registerLoginMethod(); 98 | } 99 | preStart(); 100 | 101 | start(); 102 | 103 | if (keepConnectionAlive) { 104 | startPingThread(); 105 | } 106 | } 107 | 108 | /** 109 | * Constructs a simple server with all possible configurations 110 | * 111 | * @param port The port to listen on 112 | * @param autoRegisterEveryClient Whether a client that connects should be registered to send it 113 | * broadcast and direct messages later 114 | * @param keepConnectionAlive Whether the connection should be kept alive using a ping package. 115 | * The transmission interval can be set using setPingInterval(int seconds). 116 | * @param useSSL Whether SSL should be used to establish a secure connection 117 | * @param muted Whether the mute mode should be activated on startup 118 | */ 119 | public Server(int port, boolean autoRegisterEveryClient, boolean keepConnectionAlive, 120 | boolean useSSL, boolean muted) { 121 | this.clients = new ArrayList(); 122 | this.port = port; 123 | this.autoRegisterEveryClient = autoRegisterEveryClient; 124 | this.muted = muted; 125 | 126 | this.secureMode = useSSL; 127 | if (secureMode) { 128 | System.setProperty("javax.net.ssl.keyStore", "ssc.store"); 129 | System.setProperty("javax.net.ssl.keyStorePassword", "SimpleServerClient"); 130 | } 131 | if (autoRegisterEveryClient) { 132 | registerLoginMethod(); 133 | } 134 | preStart(); 135 | 136 | start(); 137 | 138 | if (keepConnectionAlive) { 139 | startPingThread(); 140 | } 141 | } 142 | 143 | /** 144 | * Mutes the console output of this instance, stack traces will still be printed.
145 | * Be careful: This will not prevent processing of messages passed to the onLog and 146 | * onLogError methods, if they were overwritten. 147 | * 148 | * @param muted true if there should be no console output 149 | */ 150 | public void setMuted(boolean muted) { 151 | this.muted = muted; 152 | } 153 | 154 | /** 155 | * Sets the interval in which ping packages should be sent to keep the connection alive. Default 156 | * is 30 seconds. 157 | * 158 | * @param seconds The interval in which ping packages should be sent 159 | */ 160 | public void setPingInterval(int seconds) { 161 | this.pingInterval = seconds * 1000; 162 | } 163 | 164 | /** 165 | * Starts the thread sending a dummy package every pingInterval seconds. Adjust the 166 | * interval using setPingInterval(int seconds). 167 | */ 168 | protected void startPingThread() { 169 | new Thread(new Runnable() { 170 | @Override 171 | public void run() { 172 | 173 | while (server != null) { 174 | try { 175 | Thread.sleep(pingInterval); 176 | } catch (InterruptedException e) { 177 | // This exception does not need to result in any further action or output 178 | } 179 | broadcastMessage(new Datapackage("_INTERNAL_PING_", "OK")); 180 | } 181 | 182 | } 183 | }).start(); 184 | } 185 | 186 | /** 187 | * Starts the listening thread waiting for messages from clients 188 | */ 189 | protected void startListening() { 190 | if (listeningThread == null && server != null) { 191 | listeningThread = new Thread(new Runnable() { 192 | 193 | @Override 194 | public void run() { 195 | while (!Thread.interrupted() && !stopped && server != null) { 196 | 197 | try { 198 | // Wait for client to connect 199 | onLog("[Server] Waiting for connection" + (secureMode ? " using SSL..." : "...")); 200 | final Socket tempSocket = server.accept(); // potential resource leak, tempSocket might not be closed! 201 | 202 | // Read the client's message 203 | ObjectInputStream ois = 204 | new ObjectInputStream(new BufferedInputStream(tempSocket.getInputStream())); 205 | Object raw = ois.readObject(); 206 | 207 | if (raw instanceof Datapackage) { 208 | final Datapackage msg = (Datapackage) raw; 209 | onLog("[Server] Message received: " + msg); 210 | 211 | // inspect all registered methods 212 | for (final String current : idMethods.keySet()) { 213 | // if the current method equals the identifier of the Datapackage... 214 | if (msg.id().equalsIgnoreCase(current)) { 215 | onLog("[Server] Executing method for identifier '" + msg.id() + "'"); 216 | // execute the Executable on a new thread 217 | new Thread(new Runnable() { 218 | @Override 219 | public void run() { 220 | // Run the method registered for the ID of this Datapackage 221 | idMethods.get(current).run(msg, tempSocket); 222 | // and close the temporary socket if it is no longer needed 223 | if (!msg.id().equals(INTERNAL_LOGIN_ID)) { 224 | try { 225 | tempSocket.close(); 226 | } catch (IOException e) { 227 | e.printStackTrace(); 228 | } 229 | } 230 | } 231 | }).start(); 232 | break; 233 | } 234 | } 235 | 236 | } 237 | 238 | } catch (SocketException e) { 239 | onLog("Server stopped."); 240 | onServerStopped(); 241 | } catch (IllegalBlockingModeException | IOException | ClassNotFoundException e) { 242 | e.printStackTrace(); 243 | } 244 | 245 | } 246 | } 247 | 248 | }); 249 | 250 | listeningThread.start(); 251 | } 252 | } 253 | 254 | /** 255 | * Sends a reply to client. This method should only be called from within the run-Method of an 256 | * Executable implementation. 257 | * 258 | * @param toSocket The socket the message should be delivered to 259 | * @param datapackageContent The content of the message to be delivered. The ID of this 260 | * Datapackage will be "REPLY". 261 | */ 262 | public synchronized void sendReply(Socket toSocket, Object... datapackageContent) { 263 | sendMessage(new RemoteClient(null, toSocket), new Datapackage("REPLY", datapackageContent)); 264 | } 265 | 266 | /** 267 | * Sends a message to a client with specified id 268 | * 269 | * @param remoteClientId The id of the client it registered on login 270 | * @param datapackageId The id of message 271 | * @param datapackageContent The content of the message 272 | */ 273 | public synchronized void sendMessage(String remoteClientId, String datapackageId, 274 | Object... datapackageContent) { 275 | sendMessage(remoteClientId, new Datapackage(datapackageId, datapackageContent)); 276 | } 277 | 278 | /** 279 | * Sends a message to a client with specified id 280 | * 281 | * @param remoteClientId The id of the client it registered on login 282 | * @param message The message 283 | */ 284 | public synchronized void sendMessage(String remoteClientId, Datapackage message) { 285 | for (RemoteClient current : clients) { 286 | if (current.getId().equals(remoteClientId)) { 287 | sendMessage(current, message); 288 | } 289 | } 290 | } 291 | 292 | /** 293 | * Sends a message to a client 294 | * 295 | * @param remoteClient The target client 296 | * @param datapackageId The id of message 297 | * @param datapackageContent The content of the message 298 | */ 299 | public synchronized void sendMessage(RemoteClient remoteClient, String datapackageId, 300 | Object... datapackageContent) { 301 | sendMessage(remoteClient, new Datapackage(datapackageId, datapackageContent)); 302 | } 303 | 304 | /** 305 | * Sends a message to a client 306 | * 307 | * @param remoteClient The target client 308 | * @param message The message 309 | */ 310 | public synchronized void sendMessage(RemoteClient remoteClient, Datapackage message) { 311 | try { 312 | // send message 313 | if (!remoteClient.getSocket().isConnected()) { 314 | throw new ConnectException("Socket not connected."); 315 | } 316 | ObjectOutputStream out = new ObjectOutputStream( 317 | new BufferedOutputStream(remoteClient.getSocket().getOutputStream())); 318 | out.writeObject(message); 319 | out.flush(); 320 | } catch (IOException e) { 321 | onLogError("[Server] [Send Message] Error: " + e.getMessage()); 322 | 323 | // if an error occured: remove client from list 324 | if (toBeDeleted != null) { 325 | toBeDeleted.add(remoteClient); 326 | } else { 327 | clients.remove(remoteClient); 328 | onClientRemoved(remoteClient); 329 | } 330 | } 331 | } 332 | 333 | /** 334 | * Broadcasts a message to a group of clients 335 | * 336 | * @param group The group name the clients registered on their login 337 | * @param message The message 338 | * @return The number of clients reached 339 | */ 340 | public synchronized int broadcastMessageToGroup(String group, Datapackage message) { 341 | toBeDeleted = new ArrayList(); 342 | 343 | // send message to all clients 344 | int txCounter = 0; 345 | for (RemoteClient current : clients) { 346 | if (current.getGroup().equals(group)) { 347 | sendMessage(current, message); 348 | txCounter++; 349 | } 350 | } 351 | 352 | // remove all clients which produced errors while sending 353 | txCounter -= toBeDeleted.size(); 354 | for (RemoteClient current : toBeDeleted) { 355 | clients.remove(current); 356 | onClientRemoved(current); 357 | } 358 | 359 | toBeDeleted = null; 360 | 361 | return txCounter; 362 | } 363 | 364 | /** 365 | * Broadcasts a message to a group of clients 366 | * 367 | * @param message The message 368 | * @return The number of clients reached 369 | */ 370 | public synchronized int broadcastMessage(Datapackage message) { 371 | toBeDeleted = new ArrayList(); 372 | 373 | // send message to all clients 374 | int txCounter = 0; 375 | for (RemoteClient current : clients) { 376 | sendMessage(current, message); 377 | txCounter++; 378 | } 379 | 380 | // remove all clients which produced errors while sending 381 | txCounter -= toBeDeleted.size(); 382 | for (RemoteClient current : toBeDeleted) { 383 | clients.remove(current); 384 | onClientRemoved(current); 385 | } 386 | 387 | toBeDeleted = null; 388 | 389 | return txCounter; 390 | } 391 | 392 | /** 393 | * Registers a method that will be executed if a message containing identifier is received 394 | * 395 | * @param identifier The ID of the message to proccess 396 | * @param executable The method to be called when a message with identifier is received 397 | */ 398 | public void registerMethod(String identifier, Executable executable) { 399 | if (identifier.equalsIgnoreCase(INTERNAL_LOGIN_ID) && autoRegisterEveryClient) { 400 | throw new IllegalArgumentException("Identifier may not be '" + INTERNAL_LOGIN_ID + "'. " 401 | + "Since v1.0.1 the server automatically registers new clients. " 402 | + "To react on new client registed, use the onClientRegisters() listener by overwriting it."); 403 | } 404 | idMethods.put(identifier, executable); 405 | } 406 | 407 | /** 408 | * Registers a login handler. This method is called only if the constructor has been applied to 409 | * register clients. 410 | */ 411 | protected void registerLoginMethod() { 412 | idMethods.put(INTERNAL_LOGIN_ID, new Executable() { 413 | @Override 414 | public void run(Datapackage msg, Socket socket) { 415 | if (msg.size() == 3) { 416 | registerClient((String) msg.get(1), (String) msg.get(2), socket); 417 | } else if (msg.size() == 2) { 418 | registerClient((String) msg.get(1), socket); 419 | } else { 420 | registerClient(UUID.randomUUID().toString(), socket); 421 | } 422 | onClientRegistered(msg, socket); 423 | onClientRegistered(); 424 | } 425 | }); 426 | } 427 | 428 | /** 429 | * Registers a client to allow sending it direct and broadcast messages later 430 | * 431 | * @param id The client's id 432 | * @param newClientSocket The client's socket 433 | */ 434 | protected synchronized void registerClient(String id, Socket newClientSocket) { 435 | clients.add(new RemoteClient(id, newClientSocket)); 436 | } 437 | 438 | /** 439 | * Registers a client to allow sending it direct and broadcast messages later 440 | * 441 | * @param id The client's id 442 | * @param group The client's group name 443 | * @param newClientSocket The client's socket 444 | */ 445 | protected synchronized void registerClient(String id, String group, Socket newClientSocket) { 446 | clients.add(new RemoteClient(id, group, newClientSocket)); 447 | } 448 | 449 | /** 450 | * Starts the server. This method is automatically called after preStart() and starts 451 | * the actual and the listening thread. 452 | */ 453 | protected void start() { 454 | stopped = false; 455 | server = null; 456 | try { 457 | 458 | if (secureMode) { 459 | server = SSLServerSocketFactory.getDefault().createServerSocket(port); 460 | } else { 461 | server = new ServerSocket(port); 462 | } 463 | 464 | } catch (IOException e) { 465 | onLogError("Error opening ServerSocket"); 466 | e.printStackTrace(); 467 | } 468 | startListening(); 469 | } 470 | 471 | /** 472 | * Stops the server 473 | * 474 | * @throws IOException If closing the ServerSocket fails 475 | */ 476 | public void stop() throws IOException { 477 | stopped = true; 478 | 479 | if (listeningThread.isAlive()) { 480 | listeningThread.interrupt(); 481 | } 482 | 483 | if (server != null) { 484 | server.close(); 485 | } 486 | } 487 | 488 | /** 489 | * Counts the number of clients registered 490 | * 491 | * @return The number of clients registered 492 | */ 493 | public synchronized int getClientCount() { 494 | return clients != null ? clients.size() : 0; 495 | } 496 | 497 | /** 498 | * Checks whether a RemoteClient with the given ID is currently connected to the server 499 | * 500 | * @param clientId The clients ID 501 | * @return true, if a RemoteClient with ID clientId is connected to the server 502 | */ 503 | public boolean isClientIdConnected(String clientId) { 504 | if (clients != null && clients.size() > 0) { 505 | // Iterate all clients connected 506 | for (RemoteClient c : clients) { 507 | // Check client exists and its socket is connected 508 | if (c.getId().equals(clientId) && c.getSocket() != null && c.getSocket().isConnected()) { 509 | return true; 510 | } 511 | } 512 | } 513 | return false; 514 | } 515 | 516 | /** 517 | * Checks whether any client is currently connected to the server 518 | * 519 | * @return true, if at least one client is connected to the server 520 | */ 521 | public boolean isAnyClientConnected() { 522 | return getClientCount() > 0; 523 | } 524 | 525 | /** 526 | * Called just before the actual server starts. Register your handler methods in here using 527 | * registerMethod(String identifier, Executable executable)! 528 | */ 529 | public abstract void preStart(); 530 | 531 | /** 532 | * Called on the listener's main thread when a new client registers 533 | */ 534 | public void onClientRegistered() { 535 | // Overwrite this method when extending this class 536 | } 537 | 538 | /** 539 | * Called on the listener's main thread when a new client registers 540 | * 541 | * @param msg The message the client registered with 542 | * @param socket The socket the client registered with. Be careful with this! You should not close 543 | * this socket, because the server should have stored it normally to reach this client 544 | * later. 545 | */ 546 | public void onClientRegistered(Datapackage msg, Socket socket) { 547 | // Overwrite this method when extending this class 548 | } 549 | 550 | /** 551 | * Called on the listener's main thread when a client is removed from the list. This normally 552 | * happens if there was a problem with its connection. You should wait for the client to connect 553 | * again. 554 | * 555 | * @param remoteClient The client that was removed from the list of reachable clients 556 | */ 557 | public void onClientRemoved(RemoteClient remoteClient) { 558 | // Overwrite this method when extending this class 559 | } 560 | 561 | /** 562 | * Called when the server finally stops after the stop () method has been called. 563 | */ 564 | public void onServerStopped() { 565 | // Overwrite this method when extending this class 566 | } 567 | 568 | /** 569 | * By default, this method is called whenever an output is to be made. If this method is not 570 | * overwritten, the output is passed to the system's default output stream (if output is not 571 | * muted).
572 | * Error messages are passed to the onLogError event listener.
573 | * Override this method to catch and process the message in a custom way. 574 | * 575 | * @param message The content of the output to be made 576 | */ 577 | public void onLog(String message) { 578 | if (!muted) { 579 | System.out.println(message); 580 | } 581 | } 582 | 583 | /** 584 | * By default, this method is called whenever an error output is to be made. If this method is not 585 | * overwritten, the output is passed to the system's default error output stream (if output is not 586 | * muted).
587 | * Non-error messages are passed to the onLog event listener.
588 | * Override this method to catch and process the message in a custom way. 589 | * 590 | * @param message The content of the error output to be made 591 | */ 592 | public void onLogError(String message) { 593 | if (!muted) { 594 | System.err.println(message); 595 | } 596 | } 597 | 598 | /** 599 | * A RemoteClient representating a client connected to this server storing an id for 600 | * identification and a socket for communication. 601 | */ 602 | protected class RemoteClient { 603 | private String id; 604 | private String group; 605 | private Socket socket; 606 | 607 | /** 608 | * Creates a RemoteClient representating a client connected to this server storing an id for 609 | * identification and a socket for communication. The client will be member of the default 610 | * group. 611 | * 612 | * @param id The clients id (to use for identification; choose a custom String) 613 | * @param socket The socket (to use for communication) 614 | */ 615 | public RemoteClient(String id, Socket socket) { 616 | this.id = id; 617 | this.group = "_DEFAULT_GROUP_"; 618 | this.socket = socket; 619 | } 620 | 621 | /** 622 | * Creates a RemoteClient representating a client connected to this server storing an id for 623 | * identification and a socket for communication. The client can be set as a member of a group 624 | * of clients to receive messages broadcasted to a group. 625 | * 626 | * @param id The clients id (to use for identification; choose a custom String) 627 | * @param group The group the client is member of 628 | * @param socket The socket (to use for communication) 629 | */ 630 | public RemoteClient(String id, String group, Socket socket) { 631 | this.id = id; 632 | this.group = group; 633 | this.socket = socket; 634 | } 635 | 636 | public String getId() { 637 | return id; 638 | } 639 | 640 | public String getGroup() { 641 | return group; 642 | } 643 | 644 | public Socket getSocket() { 645 | return socket; 646 | } 647 | 648 | /** 649 | * Returns a String representing the RemoteClient, format is [RemoteClient ID (GROUP) @ 650 | * SOCKET_REMOTE_ADDRESS] 651 | */ 652 | @Override 653 | public String toString() { 654 | return "[RemoteClient: " + id + " (" + group + ") @ " + socket.getRemoteSocketAddress() + "]"; 655 | } 656 | } 657 | 658 | } 659 | -------------------------------------------------------------------------------- /ssc.store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DeBukkIt/SimpleServerClient/509e8f0d3aeb96919efbc40851742a7e14bfadb8/ssc.store --------------------------------------------------------------------------------