├── .gitignore ├── LICENSE ├── README.md ├── pom.xml └── src └── main └── java └── com └── sib └── simple ├── Main.java ├── eventloop ├── Main.java ├── SimpleEventHandler.java ├── SimpleEventLoop.java ├── SimpleTimer.java ├── SimpleTimerCallback.java └── SleepEvent.java └── network ├── Client.java ├── ClientCallback.java ├── Server.java ├── ServerCallback.java └── msg └── HBMsg.java /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | 3 | # Mobile Tools for Java (J2ME) 4 | .mtj.tmp/ 5 | 6 | # Package Files # 7 | *.jar 8 | *.war 9 | *.ear 10 | 11 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 12 | hs_err_pid* 13 | 14 | .idea 15 | target 16 | *.iml -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | 341 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Simple Event Loop 2 | This is a simple event loop for multi-threaded java application. 3 | Get it from [Maven repository](http://mvnrepository.com/artifact/com.github.induwarabas/event-loop) 4 | ```xml 5 | 6 | com.github.induwarabas 7 | event-loop 8 | 1.0.0 9 | 10 | ``` 11 | 12 | An event loop has its own java Thread and all callbacks are triggered in that thread context. It also contains a transfer queue implementation. 13 | 14 | ###Communicating between two threads. 15 | Communicating between two threads is simple. No locks required. 16 | Here is a sample code to send an object to the event loop. 17 | ```java 18 | // Creating new event loop 19 | SimpleEventLoop s1 = new SimpleEventLoop(); 20 | 21 | // Starting. This will create a new thread. 22 | s1.start(); 23 | 24 | // Add event handler for the event loop. This will receive Objects queue from anywhere. 25 | s1.addEventHandler(new SimpleEventHandler() { 26 | @Override 27 | public void onEvent(SimpleEventLoop eventLoop, Object data) { 28 | if (data instanceof String) { 29 | // The String sent from main thread will receive here 30 | System.out.println("Received: " + data.toString()); 31 | } 32 | } 33 | }); 34 | 35 | // Sending String from main thread. 36 | s1.queue("Hello"); 37 | ``` 38 | 39 | ###Creating timers 40 | You can create timers in both singleShot and repeatable ways. 41 | 42 | #####Single Shot timers. 43 | These timers will call only once and these are not repeatable. 44 | ```java 45 | // Creating new event loop 46 | SimpleEventLoop s1 = new SimpleEventLoop(); 47 | 48 | // Starting. This will create a new thread. 49 | s1.start(); 50 | 51 | // Creating a timer 52 | SimpleTimer timer = s1.createTimer(new SimpleTimerCallback() { 53 | @Override 54 | public void onTimer(SimpleTimer timer) { 55 | System.out.println("I am in the timer"); 56 | } 57 | }); 58 | 59 | // Specify time interval in milliseconds and call singleShot 60 | timer.singleShot(1000); 61 | ``` 62 | 63 | #####Repeating timers 64 | These timers will repeat until stop it. 65 | ```java 66 | // Creating new event loop 67 | SimpleEventLoop loop = new SimpleEventLoop(); 68 | 69 | // Starting. This will create a new thread. 70 | loop.start(); 71 | 72 | // Creating a timer 73 | SimpleTimer timer = loop.createTimer(new SimpleTimerCallback() { 74 | @Override 75 | public void onTimer(SimpleTimer timer) { 76 | System.out.println("I am in the timer"); 77 | } 78 | }); 79 | 80 | // Specify time interval in milliseconds call start 81 | timer.start(1000); 82 | ``` 83 | 84 | ###Sleeping in events 85 | If you call `Thread.sleep` in event callbacks, the event loop will get blocked. All other events will not trigger until you wake. But sometimes you may need to give a change to process another event while sleeping. You can do it by calling the `sleep` function of the event loop. 86 | See the difference of two scenarios. 87 | 88 | #####Scenario 1. Sleeping with Thread.sleep 89 | ```java 90 | // Creating new event loop 91 | SimpleEventLoop loop = new SimpleEventLoop(); 92 | 93 | // Starting. This will create a new thread. 94 | loop.start(); 95 | 96 | // Creating a timer 97 | SimpleTimer timer1 = loop.createTimer(new SimpleTimerCallback() { 98 | @Override 99 | public void onTimer(SimpleTimer timer) { 100 | System.out.println("I am going to sleep in timer 1"); 101 | try { 102 | Thread.sleep(5000); 103 | } catch (InterruptedException e) { 104 | e.printStackTrace(); 105 | } 106 | System.out.println("I waked in timer 1"); 107 | } 108 | }); 109 | timer1.start(10000); 110 | 111 | // Creating another timer 112 | SimpleTimer timer2 = loop.createTimer(new SimpleTimerCallback() { 113 | @Override 114 | public void onTimer(SimpleTimer timer) { 115 | System.out.println("Grrrrr"); 116 | } 117 | }); 118 | timer2.start(1000); 119 | ``` 120 | Output 121 | ``` 122 | I am going to sleep in timer 1 123 | I waked in timer 1 124 | Grrrrr 125 | Grrrrr 126 | Grrrrr 127 | Grrrrr 128 | Grrrrr 129 | Grrrrr 130 | Grrrrr 131 | Grrrrr 132 | Grrrrr 133 | Grrrrr 134 | I am going to sleep in timer 1 135 | I waked in timer 1 136 | Grrrrr 137 | Grrrrr 138 | Grrrrr 139 | Grrrrr 140 | Grrrrr 141 | Grrrrr 142 | Grrrrr 143 | Grrrrr 144 | ``` 145 | Here timer2 events queued until timer1 wake. 146 | 147 | #####Scenario 2. Sleeping with loop.sleep 148 | ```java 149 | // Creating new event loop 150 | SimpleEventLoop loop = new SimpleEventLoop(); 151 | 152 | // Starting. This will create a new thread. 153 | loop.start(); 154 | 155 | // Creating a timer 156 | SimpleTimer timer1 = loop.createTimer(new SimpleTimerCallback() { 157 | @Override 158 | public void onTimer(SimpleTimer timer) { 159 | System.out.println("I am going to sleep in timer 1"); 160 | loop.sleep(5000); 161 | System.out.println("I waked in timer 1"); 162 | } 163 | }); 164 | timer1.start(10000); 165 | 166 | // Creating another timer 167 | SimpleTimer timer2 = loop.createTimer(new SimpleTimerCallback() { 168 | @Override 169 | public void onTimer(SimpleTimer timer) { 170 | System.out.println("Grrrrr"); 171 | } 172 | }); 173 | timer2.start(1000); 174 | ``` 175 | Output 176 | ``` 177 | I am going to sleep in timer 1 178 | Grrrrr 179 | Grrrrr 180 | Grrrrr 181 | Grrrrr 182 | Grrrrr 183 | I waked in timer 1 184 | Grrrrr 185 | Grrrrr 186 | Grrrrr 187 | Grrrrr 188 | Grrrrr 189 | I am going to sleep in timer 1 190 | Grrrrr 191 | Grrrrr 192 | Grrrrr 193 | Grrrrr 194 | Grrrrr 195 | I waked in timer 1 196 | ``` 197 | Here the timer2 events triggered while timer1 is sleeping. 198 | 199 | ###Network communication 200 | You can create a server client application easy using the event loop. 201 | #####Creating a server 202 | ```java 203 | SimpleEventLoop loop = new SimpleEventLoop(); 204 | loop.start(); 205 | 206 | Server server = loop.createServer(new ServerCallback() { 207 | @Override 208 | public void onData(Server server, Client client, Object message) { 209 | System.out.println("Data from client: " + client.getName() + " : " + message.toString()); 210 | try { 211 | client.send("Hello Client"); 212 | } catch (IOException e) { 213 | e.printStackTrace(); 214 | } 215 | } 216 | 217 | @Override 218 | public void onDisconnected(Server server, Client client) { 219 | System.out.println("Client disconnected. " + client.getName()); 220 | } 221 | 222 | @Override 223 | public void onConnect(Server server, Client client) { 224 | System.out.println("Connected new client. "); 225 | client.setName("Client1"); 226 | } 227 | }); 228 | 229 | try { 230 | server.start(3000); 231 | } catch (IOException e) { 232 | e.printStackTrace(); 233 | } 234 | ``` 235 | 236 | #####Creating a client 237 | ```java 238 | SimpleEventLoop loop2 = new SimpleEventLoop(); 239 | loop2.start(); 240 | 241 | Client client = loop2.createClient(new ClientCallback() { 242 | @Override 243 | public void onData(Client client, Object message) { 244 | System.out.println("Data from server: " + message); 245 | } 246 | 247 | @Override 248 | public void onDisconnected(Client client) { 249 | System.out.println("Client disconnected"); 250 | } 251 | 252 | @Override 253 | public void onConnect(Client client) { 254 | System.out.println("Client connected"); 255 | } 256 | }); 257 | try { 258 | client.connect("localhost", 3000); 259 | client.waitForConnect(); 260 | client.send("Hello Server"); 261 | } catch (Exception e) { 262 | e.printStackTrace(); 263 | } 264 | ``` 265 | 266 | If you have any question feel free to contact me induwarabas@gmail.com 267 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | com.sib.simple 5 | 1.0.3-SNAPSHOT 6 | 7 | 8 | org.apache.mina 9 | mina-core 10 | 2.0.9 11 | 12 | 13 | joda-time 14 | joda-time 15 | 2.8.2 16 | 17 | 18 | event-loop 19 | 20 | 21 | MIT License 22 | http://www.opensource.org/licenses/mit-license.php 23 | 24 | 25 | 26 | 27 | Supun Induwara 28 | induwarabas@gmail.com 29 | https://github.com/induwarabas/simple-event-loop 30 | +5:30 31 | 32 | developer 33 | 34 | 35 | 36 | 37 | Simple Event Loop 38 | Simple Event Loop for simple java asynchronous multi-threaded applications 39 | https://github.com/induwarabas/simple-event-loop 40 | 41 | 42 | https://github.com/induwarabas/simple-event-loop 43 | scm:git:git@github.com:induwarabas/simple-event-loop.git 44 | HEAD 45 | 46 | 47 | 48 | UTF-8 49 | 1.8 50 | 1.8 51 | 52 | 53 | 54 | 55 | 56 | org.apache.maven.plugins 57 | maven-release-plugin 58 | 59 | true 60 | false 61 | 62 | release 63 | deploy 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | release 73 | 74 | 75 | 76 | org.apache.maven.plugins 77 | maven-source-plugin 78 | 79 | 80 | attach-sources 81 | 82 | jar-no-fork 83 | 84 | 85 | 86 | 87 | 88 | org.apache.maven.plugins 89 | maven-javadoc-plugin 90 | 91 | 92 | attach-javadocs 93 | 94 | jar 95 | 96 | 97 | 98 | 99 | 100 | org.apache.maven.plugins 101 | maven-gpg-plugin 102 | 103 | 104 | sign-artifacts 105 | verify 106 | 107 | sign 108 | 109 | 110 | 111 | 112 | 113 | org.sonatype.plugins 114 | nexus-staging-maven-plugin 115 | true 116 | 117 | ossrh 118 | https://oss.sonatype.org/ 119 | true 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | ossrh 130 | Maven Central Snapshot Repository 131 | https://oss.sonatype.org/content/repositories/snapshots 132 | 133 | 134 | ossrh 135 | Maven Central Staging Repository 136 | https://oss.sonatype.org/service/local/staging/deploy/maven2/ 137 | 138 | 139 | -------------------------------------------------------------------------------- /src/main/java/com/sib/simple/Main.java: -------------------------------------------------------------------------------- 1 | package com.sib.simple; 2 | 3 | 4 | import com.sib.simple.eventloop.SimpleEventLoop; 5 | import com.sib.simple.eventloop.SimpleTimer; 6 | import com.sib.simple.eventloop.SimpleTimerCallback; 7 | import com.sib.simple.network.Client; 8 | import com.sib.simple.network.ClientCallback; 9 | import com.sib.simple.network.Server; 10 | import com.sib.simple.network.ServerCallback; 11 | 12 | import java.io.IOException; 13 | 14 | /** 15 | * Created by Supun on 7/18/2015 16 | */ 17 | public class Main { 18 | public static void main(String[] args) throws Exception { 19 | SimpleEventLoop l1 = new SimpleEventLoop(); 20 | l1.start(); 21 | 22 | SimpleEventLoop l2 = new SimpleEventLoop(); 23 | l2.start(); 24 | 25 | Server server = l1.createServer(new ServerCallback() { 26 | public void onData(Server server, Client client, Object message) { 27 | System.out.println("onData(Server server, Client client, Object message)"); 28 | } 29 | 30 | public void onDisconnected(Server server, Client client) { 31 | System.out.println("onDisconnected(Server server, Client client) "); 32 | } 33 | 34 | public void onConnect(Server server, Client client) { 35 | System.out.println("onConnect(Server server, Client client)"); 36 | } 37 | }); 38 | server.start(5000); 39 | 40 | final Client client = l2.createClient(new ClientCallback() { 41 | public void onData(Client client, Object message) { 42 | System.out.println("onData(Client client, Object message)"); 43 | } 44 | 45 | public void onDisconnected(Client client) { 46 | System.out.println("onDisconnected(Client client)"); 47 | } 48 | 49 | public void onConnect(Client client) { 50 | System.out.println("onConnect(Client client)"); 51 | } 52 | }); 53 | 54 | client.connect("localhost",5000); 55 | client.waitForConnect(); 56 | l2.createTimer(new SimpleTimerCallback() { 57 | public void onTimer(SimpleTimer timer) { 58 | try { 59 | client.send("GRRR"); 60 | } catch (IOException e) { 61 | e.printStackTrace(); 62 | } 63 | } 64 | }).start(1000); 65 | 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/com/sib/simple/eventloop/Main.java: -------------------------------------------------------------------------------- 1 | package com.sib.simple.eventloop; 2 | 3 | /** 4 | * Created by Supun on 7/18/2015 5 | */ 6 | public class Main { 7 | public static void main(String[] args) { 8 | final SimpleEventLoop s1 = new SimpleEventLoop(); 9 | s1.start(); 10 | s1.createTimer(new SimpleTimerCallback() { 11 | @Override 12 | public void onTimer(SimpleTimer timer) { 13 | System.out.println("Hoooo"); 14 | s1.sleep(5000); 15 | System.out.println("Booo"); 16 | } 17 | }).start(3000); 18 | s1.createTimer(new SimpleTimerCallback() { 19 | @Override 20 | public void onTimer(SimpleTimer timer) { 21 | System.out.println("Sleeping1"); 22 | s1.sleep(5000); 23 | System.out.println("Waked"); 24 | 25 | System.out.println("Sleeping2"); 26 | s1.sleep(5000); 27 | System.out.println("Waked2"); 28 | } 29 | }).singleShot(1000); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/sib/simple/eventloop/SimpleEventHandler.java: -------------------------------------------------------------------------------- 1 | package com.sib.simple.eventloop; 2 | 3 | /** 4 | * Created by Supun on 7/18/2015 5 | */ 6 | public interface SimpleEventHandler { 7 | void onEvent(SimpleEventLoop eventLoop, Object data); 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/sib/simple/eventloop/SimpleEventLoop.java: -------------------------------------------------------------------------------- 1 | package com.sib.simple.eventloop; 2 | 3 | import com.sib.simple.network.Client; 4 | import com.sib.simple.network.ClientCallback; 5 | import com.sib.simple.network.Server; 6 | import com.sib.simple.network.ServerCallback; 7 | 8 | import java.util.*; 9 | 10 | /** 11 | * Created by Supun on 7/17/2015 12 | */ 13 | public class SimpleEventLoop implements Runnable { 14 | private static class Data { 15 | public final Queue tqueue = new LinkedList<>(); 16 | Set callback = new HashSet<>(); 17 | private boolean isActive = false; 18 | } 19 | 20 | final Data data; 21 | 22 | String name = UUID.randomUUID().toString(); 23 | 24 | public SimpleEventLoop() { 25 | this.data = new Data(); 26 | } 27 | 28 | private SimpleEventLoop(Data data) { 29 | this.data = data; 30 | } 31 | 32 | public void addEventHandler(SimpleEventHandler handler) { 33 | this.data.callback.add(handler); 34 | } 35 | 36 | public SimpleTimer createTimer(SimpleTimerCallback timerCallback) { 37 | return new SimpleTimer(this, timerCallback); 38 | } 39 | 40 | public Server createServer(ServerCallback callback) { 41 | return new Server(this, callback); 42 | } 43 | 44 | public Client createClient(ClientCallback callback) { 45 | return new Client(this, callback); 46 | } 47 | 48 | public void start() { 49 | if (!data.isActive) { 50 | new Thread(this).start(); 51 | } 52 | } 53 | 54 | public void stop() { 55 | data.isActive = false; 56 | synchronized (data.tqueue) { 57 | data.tqueue.notify(); 58 | } 59 | } 60 | 61 | public void run() { 62 | data.isActive = true; 63 | boolean breakBySleep = false; 64 | while (data.isActive) { 65 | while (true) { 66 | Object obj; 67 | synchronized (data.tqueue) { 68 | obj = data.tqueue.poll(); 69 | } 70 | if (obj == null) { 71 | break; 72 | } 73 | if (obj instanceof SimpleTimer.Event) { 74 | SimpleTimer.Event event = (SimpleTimer.Event)obj; 75 | event.getTimer().getCallback().onTimer(event.getTimer()); 76 | } else if (obj instanceof Server.Event) { 77 | Server.Event serverEvent = (Server.Event)obj; 78 | serverEvent.getServer().onEvent(serverEvent); 79 | }else if (obj instanceof Client.Event) { 80 | Client.Event clientEvent = (Client.Event)obj; 81 | clientEvent.getClient().onEvent(clientEvent); 82 | } else if(obj instanceof SleepEvent) { 83 | SleepEvent event = (SleepEvent)obj; 84 | event.setCompleted(true); 85 | synchronized (event) { 86 | event.notify(); 87 | } 88 | breakBySleep = true; 89 | break; 90 | } else if (data.callback != null){ 91 | for (SimpleEventHandler handler : data.callback) { 92 | handler.onEvent(this, obj); 93 | } 94 | } 95 | synchronized (data.tqueue) { 96 | if (data.tqueue.isEmpty()) { 97 | break; 98 | } 99 | } 100 | } 101 | if (breakBySleep) { 102 | break; 103 | } 104 | try { 105 | synchronized (data.tqueue) { 106 | data.tqueue.wait(); 107 | } 108 | } catch (InterruptedException e) { 109 | e.printStackTrace(); 110 | } 111 | } 112 | } 113 | 114 | public void queue(Object object) { 115 | if (!data.isActive) { 116 | return; 117 | } 118 | if (object == null) { 119 | throw new NullPointerException("Cannot queue a null object"); 120 | } 121 | synchronized (data.tqueue) { 122 | data.tqueue.add(object); 123 | data.tqueue.notify(); 124 | } 125 | } 126 | 127 | public void sleep(long mills) { 128 | SleepEvent event = new SleepEvent(); 129 | createTimer(new SimpleTimerCallback() { 130 | @Override 131 | public void onTimer(SimpleTimer timer) { 132 | queue(event); 133 | } 134 | }).singleShot(mills); 135 | new Thread(new SimpleEventLoop(data)).start(); 136 | while (!event.isCompleted()) { 137 | try { 138 | synchronized (event) { 139 | event.wait(); 140 | } 141 | } catch (InterruptedException e) { 142 | e.printStackTrace(); 143 | } 144 | } 145 | } 146 | } 147 | -------------------------------------------------------------------------------- /src/main/java/com/sib/simple/eventloop/SimpleTimer.java: -------------------------------------------------------------------------------- 1 | package com.sib.simple.eventloop; 2 | 3 | /** 4 | * Created by Supun on 7/18/2015 5 | */ 6 | public class SimpleTimer { 7 | class Event { 8 | private final SimpleTimer timer; 9 | 10 | Event(SimpleTimer timer) { 11 | this.timer = timer; 12 | } 13 | 14 | public SimpleTimer getTimer() { 15 | return timer; 16 | } 17 | } 18 | 19 | private SimpleEventLoop eventLoop; 20 | long mills; 21 | private boolean isActive = false; 22 | private final SimpleTimerCallback callback; 23 | 24 | public SimpleTimer(SimpleEventLoop eventLoop, SimpleTimerCallback callback) { 25 | this.eventLoop = eventLoop; 26 | this.callback = callback; 27 | } 28 | 29 | public void stop() { 30 | isActive = false; 31 | } 32 | 33 | SimpleTimerCallback getCallback() { 34 | return callback; 35 | } 36 | 37 | public void singleShot(final long mills) { 38 | final SimpleTimer st = this; 39 | isActive = true; 40 | new Thread(new Runnable() { 41 | public void run() { 42 | if (isActive) { 43 | try { 44 | Thread.sleep(mills); 45 | isActive = false; 46 | eventLoop.queue(new Event(st)); 47 | } catch (InterruptedException e) { 48 | e.printStackTrace(); 49 | } 50 | } 51 | isActive = false; 52 | } 53 | }).start(); 54 | } 55 | 56 | public void start(final long mills) { 57 | this.mills = mills; 58 | isActive = true; 59 | final SimpleTimer st = this; 60 | new Thread(new Runnable() { 61 | public void run() { 62 | while (isActive) { 63 | try { 64 | eventLoop.queue(new Event(st)); 65 | Thread.sleep(mills); 66 | } catch (InterruptedException e) { 67 | e.printStackTrace(); 68 | } 69 | } 70 | } 71 | }).start(); 72 | } 73 | 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/com/sib/simple/eventloop/SimpleTimerCallback.java: -------------------------------------------------------------------------------- 1 | package com.sib.simple.eventloop; 2 | 3 | /** 4 | * Created by Supun on 7/18/2015 5 | */ 6 | public interface SimpleTimerCallback { 7 | void onTimer(SimpleTimer timer); 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/sib/simple/eventloop/SleepEvent.java: -------------------------------------------------------------------------------- 1 | package com.sib.simple.eventloop; 2 | 3 | /** 4 | * Created by Supun on 7/18/2015 5 | */ 6 | public class SleepEvent { 7 | private boolean completed = false; 8 | 9 | public SleepEvent() { 10 | 11 | } 12 | 13 | public boolean isCompleted() { 14 | return completed; 15 | } 16 | 17 | public void setCompleted(boolean completed) { 18 | this.completed = completed; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/sib/simple/network/Client.java: -------------------------------------------------------------------------------- 1 | package com.sib.simple.network; 2 | 3 | import com.sib.simple.eventloop.SimpleEventLoop; 4 | import com.sib.simple.network.msg.HBMsg; 5 | import org.apache.mina.core.future.CloseFuture; 6 | import org.apache.mina.core.future.ConnectFuture; 7 | import org.apache.mina.core.service.IoHandler; 8 | import org.apache.mina.core.session.IdleStatus; 9 | import org.apache.mina.core.session.IoSession; 10 | import org.apache.mina.filter.codec.ProtocolCodecFilter; 11 | import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory; 12 | import org.apache.mina.transport.socket.nio.NioSocketConnector; 13 | import org.joda.time.DateTime; 14 | 15 | import java.io.IOException; 16 | import java.net.InetSocketAddress; 17 | import java.util.concurrent.ExecutionException; 18 | 19 | /** 20 | * Created by Supun on 7/14/2015 21 | */ 22 | public class Client implements IoHandler { 23 | 24 | public static class Event { 25 | 26 | private final Client client; 27 | private final ClientCallback callback; 28 | 29 | public Event(Client client, ClientCallback callback) { 30 | this.client = client; 31 | this.callback = callback; 32 | } 33 | 34 | public Client getClient() { 35 | return client; 36 | } 37 | 38 | public ClientCallback getCallback() { 39 | return callback; 40 | } 41 | } 42 | 43 | public static class EventOnDisconnect extends Event { 44 | 45 | public EventOnDisconnect(Client client, ClientCallback callback) { 46 | super(client, callback); 47 | } 48 | } 49 | 50 | public static class EventOnConnect extends Event { 51 | 52 | public EventOnConnect(Client client, ClientCallback callback) { 53 | super(client, callback); 54 | } 55 | } 56 | 57 | public static class EventOnData extends Event { 58 | private final Object data; 59 | 60 | public EventOnData(Client client, ClientCallback callback, Object data) { 61 | super(client, callback); 62 | this.data = data; 63 | } 64 | 65 | public Object getData() { 66 | return data; 67 | } 68 | } 69 | 70 | private String name = ""; 71 | private String host; 72 | private int port; 73 | NioSocketConnector connector; 74 | IoSession session; 75 | ClientCallback callback; 76 | ServerCallback serverCallback; 77 | Server server; 78 | private final SimpleEventLoop loop; 79 | ConnectFuture future; 80 | 81 | public Client(SimpleEventLoop loop, ClientCallback callback) { 82 | this.callback = callback; 83 | this.loop = loop; 84 | } 85 | 86 | public Client(SimpleEventLoop loop, Server server, ServerCallback callback, IoSession session) throws IOException { 87 | this.loop = loop; 88 | this.server = server; 89 | this.serverCallback = callback; 90 | this.session = session; 91 | System.out.println(host + ":" + port); 92 | loop.queue(new Server.EventOnConnect(server, this, serverCallback)); 93 | } 94 | 95 | public void connect(String host, int port) throws IOException, ExecutionException, InterruptedException { 96 | this.host = host; 97 | this.port = port; 98 | connector = new NioSocketConnector(); 99 | connector.setConnectTimeoutMillis(4000); 100 | connector.getFilterChain().addLast("codec", 101 | new ProtocolCodecFilter(new ObjectSerializationCodecFactory())); 102 | connector.getSessionConfig().setIdleTime(IdleStatus.WRITER_IDLE, 10); 103 | connector.getSessionConfig().setIdleTime(IdleStatus.READER_IDLE, 10); 104 | connector.getSessionConfig().setReceiveBufferSize(2048); 105 | connector.setHandler(this); 106 | System.out.println("Connecting.. " + host + ":" + port + DateTime.now().toString()); 107 | future = connector.connect(new InetSocketAddress(host, port)); 108 | } 109 | 110 | public void waitForConnect() throws Exception { 111 | future.awaitUninterruptibly(); 112 | session = future.getSession(); 113 | } 114 | 115 | public void onEvent(Event event) { 116 | if (event instanceof EventOnConnect) { 117 | event.getCallback().onConnect(event.getClient()); 118 | } else if (event instanceof EventOnDisconnect) { 119 | event.getCallback().onDisconnected(event.getClient()); 120 | } else if (event instanceof EventOnData) { 121 | EventOnData data = (EventOnData) event; 122 | event.getCallback().onData(event.getClient(), data.getData()); 123 | } 124 | } 125 | 126 | public String getName() { 127 | return name; 128 | } 129 | 130 | public void setName(String name) { 131 | this.name = name; 132 | } 133 | 134 | public synchronized void send(Object object) throws IOException { 135 | session.write(object); 136 | } 137 | 138 | public synchronized void disconnect() throws IOException { 139 | session.close(true); 140 | } 141 | 142 | @Override 143 | public void sessionCreated(IoSession session) throws Exception { 144 | 145 | } 146 | 147 | @Override 148 | public void sessionOpened(IoSession session) throws Exception { 149 | this.session = session; 150 | loop.queue(new Client.EventOnConnect(this, callback)); 151 | } 152 | 153 | @Override 154 | public void sessionClosed(IoSession session) throws Exception { 155 | loop.queue(new Client.EventOnDisconnect(this, callback)); 156 | connector.dispose(); 157 | } 158 | 159 | @Override 160 | public void sessionIdle(IoSession session, IdleStatus status) throws Exception { 161 | //System.out.println("CLIENT: IDLE " + status + " " + session.getAttribute("idle")); 162 | //System.out.println("Client: " + status + " " + session.getAttribute("idle") + " IIDDDEEEELLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL"); 163 | if (status == IdleStatus.WRITER_IDLE) { 164 | session.write(new HBMsg()); 165 | } 166 | if (status == IdleStatus.READER_IDLE) { 167 | Integer idle = (Integer)session.getAttribute("idle"); 168 | if (idle == null) { 169 | idle = 0; 170 | } 171 | ++idle; 172 | session.setAttribute("idle", idle); 173 | if (idle == 5) { 174 | //System.out.println("Client: CCCLLLOOOSSSINNNGGGG Session due to inactivity."); 175 | session.close(true); 176 | } 177 | } 178 | } 179 | 180 | @Override 181 | public void exceptionCaught(IoSession session, Throwable cause) throws Exception { 182 | session.close(true); 183 | } 184 | 185 | @Override 186 | public void messageReceived(IoSession session, Object message) throws Exception { 187 | session.setAttribute("idle", 0); 188 | if (message instanceof HBMsg) { 189 | return; 190 | } 191 | loop.queue(new Client.EventOnData(this, callback, message)); 192 | } 193 | 194 | @Override 195 | public void messageSent(IoSession session, Object message) throws Exception { 196 | 197 | } 198 | 199 | @Override 200 | public void inputClosed(IoSession session) throws Exception { 201 | session.close(true); 202 | } 203 | } 204 | -------------------------------------------------------------------------------- /src/main/java/com/sib/simple/network/ClientCallback.java: -------------------------------------------------------------------------------- 1 | package com.sib.simple.network; 2 | 3 | /** 4 | * Created by Supun on 7/15/2015 5 | */ 6 | public interface ClientCallback { 7 | void onData(Client client, Object message); 8 | void onDisconnected(Client client); 9 | void onConnect(Client client); 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/sib/simple/network/Server.java: -------------------------------------------------------------------------------- 1 | package com.sib.simple.network; 2 | 3 | import com.sib.simple.eventloop.SimpleEventLoop; 4 | import com.sib.simple.network.msg.HBMsg; 5 | import org.apache.mina.core.service.IoHandler; 6 | import org.apache.mina.core.session.IdleStatus; 7 | import org.apache.mina.core.session.IoSession; 8 | import org.apache.mina.filter.codec.ProtocolCodecFilter; 9 | import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory; 10 | import org.apache.mina.transport.socket.nio.NioSocketAcceptor; 11 | 12 | import java.io.IOException; 13 | import java.net.InetSocketAddress; 14 | 15 | /** 16 | * Created by Supun on 7/18/2015 17 | */ 18 | public class Server implements IoHandler { 19 | ServerCallback callback; 20 | private final SimpleEventLoop loop; 21 | NioSocketAcceptor acceptor; 22 | 23 | 24 | 25 | public static class Event { 26 | 27 | private final Client client; 28 | private final Server server; 29 | private final ServerCallback callback; 30 | 31 | public Event(Server server, Client client, ServerCallback callback) { 32 | this.client = client; 33 | this.server = server; 34 | this.callback = callback; 35 | } 36 | 37 | public Client getClient() { 38 | return client; 39 | } 40 | 41 | public Server getServer() { 42 | return server; 43 | } 44 | 45 | public ServerCallback getCallback() { 46 | return callback; 47 | } 48 | } 49 | 50 | public static class EventOnDisconnect extends Event{ 51 | 52 | public EventOnDisconnect(Server server, Client client, ServerCallback callback) { 53 | super(server, client, callback); 54 | } 55 | } 56 | 57 | public static class EventOnConnect extends Event{ 58 | 59 | public EventOnConnect(Server server, Client client, ServerCallback callback) { 60 | super(server, client, callback); 61 | } 62 | } 63 | 64 | public static class EventOnData extends Event{ 65 | private final Object data; 66 | public EventOnData(Server server, Client client, ServerCallback callback, Object data) { 67 | super(server, client, callback); 68 | this.data = data; 69 | } 70 | public Object getData() { 71 | return data; 72 | } 73 | } 74 | 75 | public Server(SimpleEventLoop loop, ServerCallback callback) { 76 | this.callback = callback; 77 | this.loop = loop; 78 | } 79 | 80 | public void start(int port) throws IOException { 81 | acceptor = new NioSocketAcceptor(); 82 | acceptor.getFilterChain().addLast( "codec", new ProtocolCodecFilter(new ObjectSerializationCodecFactory())); 83 | acceptor.setHandler(this); 84 | acceptor.getSessionConfig().setReadBufferSize( 2048 ); 85 | acceptor.getSessionConfig().setIdleTime( IdleStatus.WRITER_IDLE, 10); 86 | acceptor.getSessionConfig().setIdleTime( IdleStatus.READER_IDLE, 10); 87 | acceptor.setReuseAddress(true); 88 | acceptor.bind(new InetSocketAddress(port)); 89 | } 90 | 91 | public void onEvent(Event event) { 92 | if (event instanceof EventOnConnect) { 93 | event.getCallback().onConnect(event.getServer(), event.getClient()); 94 | } else if (event instanceof EventOnDisconnect) { 95 | event.getCallback().onDisconnected(event.getServer(), event.getClient()); 96 | } else if (event instanceof EventOnData) { 97 | EventOnData data = (EventOnData) event; 98 | event.getCallback().onData(event.getServer(), event.getClient(), data.getData()); 99 | } 100 | } 101 | 102 | public void stop() throws IOException { 103 | if (acceptor != null) { 104 | acceptor.dispose(); 105 | acceptor = null; 106 | } 107 | } 108 | 109 | @Override 110 | public void sessionCreated(IoSession session) throws Exception { 111 | Client c = new Client(loop, this, callback, session); 112 | session.setAttribute("client", c); 113 | } 114 | 115 | @Override 116 | public void sessionOpened(IoSession session) throws Exception { 117 | 118 | } 119 | 120 | @Override 121 | public void sessionClosed(IoSession session) throws Exception { 122 | loop.queue(new Server.EventOnDisconnect(this, (Client)session.getAttribute("client"), callback)); 123 | } 124 | 125 | @Override 126 | public void sessionIdle(IoSession session, IdleStatus status) throws Exception { 127 | //System.out.println("SERVER: IDLE " + status + " " + session.getAttribute("idle")); 128 | //System.out.println("Server: " + status + " " + session.getAttribute("idle") + " IIDDDEEEELLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL"); 129 | if (status == IdleStatus.WRITER_IDLE || status == IdleStatus.BOTH_IDLE) { 130 | session.write(new HBMsg()); 131 | } 132 | if (status == IdleStatus.READER_IDLE || status == IdleStatus.BOTH_IDLE) { 133 | Integer idle = (Integer)session.getAttribute("idle"); 134 | if (idle == null) { 135 | idle = 0; 136 | } 137 | ++idle; 138 | session.setAttribute("idle", idle); 139 | if (idle == 5) { 140 | //System.out.println("Server: CCCLLLOOOSSSINNNGGGG Session due to inactivity."); 141 | session.close(true); 142 | } 143 | } 144 | } 145 | 146 | @Override 147 | public void exceptionCaught(IoSession session, Throwable cause) throws Exception { 148 | session.close(true); 149 | } 150 | 151 | @Override 152 | public void messageReceived(IoSession session, Object message) throws Exception { 153 | session.setAttribute("idle", 0); 154 | if (message instanceof HBMsg) { 155 | return; 156 | } 157 | loop.queue(new Server.EventOnData(this, (Client)session.getAttribute("client"), callback, message)); 158 | } 159 | 160 | @Override 161 | public void messageSent(IoSession session, Object message) throws Exception { 162 | 163 | } 164 | 165 | @Override 166 | public void inputClosed(IoSession session) throws Exception { 167 | session.close(true); 168 | } 169 | } 170 | -------------------------------------------------------------------------------- /src/main/java/com/sib/simple/network/ServerCallback.java: -------------------------------------------------------------------------------- 1 | package com.sib.simple.network; 2 | 3 | /** 4 | * Created by Supun on 7/15/2015 5 | */ 6 | public interface ServerCallback { 7 | void onData(Server server, Client client, Object message); 8 | void onDisconnected(Server server, Client client); 9 | void onConnect(Server server, Client client); 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/sib/simple/network/msg/HBMsg.java: -------------------------------------------------------------------------------- 1 | package com.sib.simple.network.msg; 2 | 3 | import java.io.Serializable; 4 | 5 | /** 6 | * Created by Supun on 8/19/2015 7 | */ 8 | public class HBMsg implements Serializable { 9 | } 10 | --------------------------------------------------------------------------------