├── .gitignore ├── LICENSE ├── README.md ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── danieljyc │ │ ├── BitcoinApplication.java │ │ ├── controller │ │ ├── BlockchainDemo.java │ │ └── HelloWorld.java │ │ ├── domain │ │ ├── BaseToString.java │ │ ├── BlockModel.java │ │ └── BlockchainModel.java │ │ ├── service │ │ ├── BlockchainService.java │ │ └── impl │ │ │ └── BlockchainServiceImpl.java │ │ └── websocket │ │ ├── client │ │ ├── BlockchainWebSocketHandler.java │ │ ├── SendMessageClient.java │ │ └── impl │ │ │ └── SendMessageClientImpl.java │ │ └── server │ │ ├── BlockchainWebSocket.java │ │ └── reverse │ │ └── ReverseWebSocketEndpoint.java └── resources │ └── application.properties └── test └── java └── com └── danieljyc └── BitcoinApplicationTests.java /.gitignore: -------------------------------------------------------------------------------- 1 | !.mvn/wrapper/maven-wrapper.jar 2 | target/ 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | 12 | ### IntelliJ IDEA ### 13 | .idea 14 | *.iws 15 | *.iml 16 | *.ipr 17 | 18 | ### NetBeans ### 19 | nbproject/private/ 20 | build/ 21 | nbbuild/ 22 | dist/ 23 | nbdist/ 24 | .nb-gradle/% -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # simpleblockchain 2 | 区块链的简单实现(Java版) 3 | 4 | 5 | - [x] Restful API 6 | - [x] WebSocket:用于C/S通信 7 | - [x] 模型 8 | - [ ] 流程:ing 9 | - [ ] 测试 10 | - [ ] 部署:Docker 11 | - [ ] 分布式联调和测试 12 | 13 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.danieljyc 7 | bitcoin 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | bitcoin 12 | Project for bitcoin 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 1.5.8.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter-jersey 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-starter-web 35 | 36 | 37 | org.springframework.boot 38 | spring-boot-starter-web-services 39 | 40 | 41 | org.springframework.boot 42 | spring-boot-starter-websocket 43 | 44 | 45 | 46 | org.springframework.boot 47 | spring-boot-starter-test 48 | test 49 | 50 | 51 | 52 | org.projectlombok 53 | lombok 54 | 1.16.16 55 | 56 | 57 | org.apache.commons 58 | commons-lang3 59 | 3.6 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | org.springframework.boot 69 | spring-boot-maven-plugin 70 | 71 | 72 | 73 | 74 | 75 | 76 | -------------------------------------------------------------------------------- /src/main/java/com/danieljyc/BitcoinApplication.java: -------------------------------------------------------------------------------- 1 | package com.danieljyc; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.boot.builder.SpringApplicationBuilder; 6 | import org.springframework.boot.web.support.SpringBootServletInitializer; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.web.bind.annotation.RestController; 9 | import org.springframework.web.socket.config.annotation.WebSocketConfigurer; 10 | import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; 11 | import org.springframework.web.socket.server.standard.ServerEndpointExporter; 12 | 13 | @RestController 14 | @SpringBootApplication 15 | public class BitcoinApplication extends SpringBootServletInitializer 16 | implements WebSocketConfigurer { 17 | 18 | @Override 19 | public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { 20 | } 21 | 22 | @Override 23 | protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { 24 | return application.sources(BitcoinApplication.class); 25 | } 26 | 27 | @Bean 28 | public ServerEndpointExporter serverEndpointExporter() { 29 | return new ServerEndpointExporter(); 30 | } 31 | 32 | public static void main(String[] args) { 33 | SpringApplication.run(BitcoinApplication.class, args); 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/danieljyc/controller/BlockchainDemo.java: -------------------------------------------------------------------------------- 1 | package com.danieljyc.controller; 2 | 3 | import com.danieljyc.websocket.client.SendMessageClient; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.web.bind.annotation.PathVariable; 6 | import org.springframework.web.bind.annotation.RequestMapping; 7 | import org.springframework.web.bind.annotation.RestController; 8 | 9 | /** 10 | * Created by DanielJyc on 2017-11-05 17:13. 11 | */ 12 | @RestController 13 | public class BlockchainDemo { 14 | 15 | @Autowired 16 | private SendMessageClient sendMessageClient; 17 | 18 | @RequestMapping(value = "/ws/{message}") 19 | public void sendMessage(@PathVariable("message") final String message) throws Exception { 20 | sendMessageClient.process(); 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/danieljyc/controller/HelloWorld.java: -------------------------------------------------------------------------------- 1 | package com.danieljyc.controller; 2 | 3 | import org.springframework.beans.factory.annotation.Value; 4 | import org.springframework.web.bind.annotation.RequestMapping; 5 | import org.springframework.web.bind.annotation.RestController; 6 | 7 | /** 8 | * Created by daniel on 2017/10/30. 9 | */ 10 | @RestController 11 | public class HelloWorld { 12 | @Value("${com.dudu.name}") 13 | private String name; 14 | @Value("${com.dudu.want}") 15 | private String want; 16 | 17 | @RequestMapping("/") 18 | public String index() { 19 | return "Hello Spring Boot3"; 20 | } 21 | 22 | 23 | @RequestMapping("/msg") 24 | public String hexo() { 25 | return name + "," + want; 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/danieljyc/domain/BaseToString.java: -------------------------------------------------------------------------------- 1 | package com.danieljyc.domain; 2 | 3 | import org.apache.commons.lang3.builder.ToStringBuilder; 4 | import org.apache.commons.lang3.builder.ToStringStyle; 5 | 6 | import java.io.Serializable; 7 | 8 | /** 9 | * Created by DanielJyc on 2017-11-05 21:16. 10 | */ 11 | public class BaseToString implements Serializable { 12 | 13 | private static final long serialVersionUID = -3531774999346449712L; 14 | 15 | @Override 16 | public String toString() { 17 | return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/danieljyc/domain/BlockModel.java: -------------------------------------------------------------------------------- 1 | package com.danieljyc.domain; 2 | 3 | import lombok.Data; 4 | 5 | /** 6 | * Created by DanielJyc on 2017-11-05 19:58. 7 | */ 8 | @Data 9 | public class BlockModel { 10 | 11 | public BlockModel(Long index, Long timestamp, String data, String hash, String preHash) { 12 | this.index = index; 13 | this.timestamp = timestamp; 14 | this.data = data; 15 | this.hash = hash; 16 | this.preHash = preHash; 17 | } 18 | 19 | /** 20 | * 区块序号 21 | */ 22 | private Long index; 23 | 24 | /** 25 | * 时间戳 26 | */ 27 | private Long timestamp; 28 | 29 | /** 30 | * 数据 31 | */ 32 | private String data; 33 | 34 | /** 35 | * 当前区块的哈希值 36 | */ 37 | private String hash; 38 | 39 | /** 40 | * 上一个区块的哈希值 41 | */ 42 | private String preHash; 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/danieljyc/domain/BlockchainModel.java: -------------------------------------------------------------------------------- 1 | package com.danieljyc.domain; 2 | 3 | import com.danieljyc.websocket.server.BlockchainWebSocket; 4 | 5 | import java.util.concurrent.CopyOnWriteArraySet; 6 | 7 | /** 8 | * Created by DanielJyc on 2017-11-05 21:15. 9 | */ 10 | public class BlockchainModel extends BaseToString { 11 | /** 12 | * concurrent包的线程安全Set,用来存放区块链。 13 | */ 14 | private static CopyOnWriteArraySet blockModels = new CopyOnWriteArraySet(); 15 | 16 | public BlockchainModel() { 17 | BlockModel blockModel = getGenesisBlock(); 18 | blockModels.add(blockModel); 19 | } 20 | 21 | /** 22 | * 创世区块,即第0个区块 23 | */ 24 | private BlockModel getGenesisBlock() { 25 | return new BlockModel(0L, 12332L, "genesis block", "816534932c2b7154836da6afc367695e6337db8a921823784c14378abed4f7d7", "0"); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/danieljyc/service/BlockchainService.java: -------------------------------------------------------------------------------- 1 | package com.danieljyc.service; 2 | 3 | import com.danieljyc.domain.BlockModel; 4 | import com.danieljyc.domain.BlockchainModel; 5 | import com.sun.org.apache.xpath.internal.operations.Bool; 6 | 7 | /** 8 | * Created by DanielJyc on 2017-11-05 21:32. 9 | */ 10 | public interface BlockchainService { 11 | /** 12 | * 产生区块 13 | * 比特币中区块是通过“挖矿”得到的,不断的计算满足某个条件的hash值,这里通过简单的计算模拟: 14 | * sha256(index+hash+data+timestamp) 15 | * 16 | * @param blockData 区块的数据 17 | * @return 区块 18 | */ 19 | BlockModel generateNextBlock(String blockData); 20 | 21 | /** 22 | * 往区块链中添加区块 23 | * 24 | * @param blockModel 被添加的区块 25 | * @return 添加结果 26 | */ 27 | Boolean addBlockToBlockchain(BlockModel blockModel); 28 | 29 | /** 30 | * 验证区块的完整性: 31 | * 实际上就是看数据是否一致,是否被篡改。计算hash进行比对。 32 | * 33 | * @param newBlock 新的当前区块 34 | * @param previousBlock 上一个区块 35 | * @return 校验结果 36 | */ 37 | Boolean isValidNewBlock(BlockModel newBlock, BlockModel previousBlock); 38 | 39 | /** 40 | * 校验区块链是否有效:校验创世区块和每个区块 41 | * 42 | * @param blockchainModel 区块链 43 | * @return 结果 44 | */ 45 | Boolean isValidChain(BlockchainModel blockchainModel); 46 | 47 | 48 | /** 49 | * 区块链合并: 50 | * 在网络中,同时会有多个矿工在挖矿,如果大家几乎同时提交,那么比特币就会出现“分叉”,那么怎么办呢? 51 | * 解决:做法很简单,就是选择最长的链。 52 | * 53 | * @param receivedBlockchainModel 被合并的区块链 54 | * @return 合并结果 55 | */ 56 | Boolean compareAndMergeBlockchain(BlockchainModel receivedBlockchainModel); 57 | 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/danieljyc/service/impl/BlockchainServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.danieljyc.service.impl; 2 | 3 | import com.danieljyc.domain.BlockModel; 4 | import com.danieljyc.domain.BlockchainModel; 5 | import com.danieljyc.service.BlockchainService; 6 | 7 | /** 8 | * Created by DanielJyc on 2017-11-05 21:32. 9 | */ 10 | public class BlockchainServiceImpl implements BlockchainService { 11 | @Override 12 | public BlockModel generateNextBlock(String blockData) { 13 | return null; 14 | } 15 | 16 | @Override 17 | public Boolean addBlockToBlockchain(BlockModel blockModel) { 18 | return null; 19 | } 20 | 21 | @Override 22 | public Boolean isValidNewBlock(BlockModel newBlock, BlockModel previousBlock) { 23 | return null; 24 | } 25 | 26 | @Override 27 | public Boolean isValidChain(BlockchainModel blockchainModel) { 28 | return null; 29 | } 30 | 31 | @Override 32 | public Boolean compareAndMergeBlockchain(BlockchainModel receivedBlockchainModel) { 33 | return null; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/danieljyc/websocket/client/BlockchainWebSocketHandler.java: -------------------------------------------------------------------------------- 1 | package com.danieljyc.websocket.client; 2 | 3 | import com.danieljyc.websocket.client.impl.SendMessageClientImpl; 4 | import org.apache.commons.logging.Log; 5 | import org.apache.commons.logging.LogFactory; 6 | import org.springframework.web.socket.TextMessage; 7 | import org.springframework.web.socket.WebSocketSession; 8 | import org.springframework.web.socket.handler.TextWebSocketHandler; 9 | 10 | /** 11 | * Created by DanielJyc on 2017-11-05 14:58. 12 | */ 13 | public class BlockchainWebSocketHandler extends TextWebSocketHandler { 14 | 15 | private Log logger = LogFactory.getLog(SendMessageClientImpl.class); 16 | 17 | @Override 18 | public void handleTextMessage(WebSocketSession session, TextMessage message) { 19 | logger.info("------- received client message ------"); 20 | logger.info(message.getPayload()); 21 | logger.info("--------- end client message ---------"); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/danieljyc/websocket/client/SendMessageClient.java: -------------------------------------------------------------------------------- 1 | package com.danieljyc.websocket.client; 2 | 3 | /** 4 | * Created by DanielJyc on 2017-11-05 17:06. 5 | */ 6 | public interface SendMessageClient { 7 | 8 | void process(); 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/danieljyc/websocket/client/impl/SendMessageClientImpl.java: -------------------------------------------------------------------------------- 1 | package com.danieljyc.websocket.client.impl; 2 | 3 | import com.danieljyc.websocket.client.BlockchainWebSocketHandler; 4 | import com.danieljyc.websocket.client.SendMessageClient; 5 | import org.apache.commons.logging.Log; 6 | import org.apache.commons.logging.LogFactory; 7 | import org.springframework.stereotype.Component; 8 | import org.springframework.web.socket.TextMessage; 9 | import org.springframework.web.socket.WebSocketSession; 10 | import org.springframework.web.socket.client.WebSocketClient; 11 | import org.springframework.web.socket.client.standard.StandardWebSocketClient; 12 | 13 | /** 14 | * Created by DanielJyc on 2017-11-05 17:07. 15 | */ 16 | @Component 17 | public class SendMessageClientImpl implements SendMessageClient { 18 | private Log logger = LogFactory.getLog(SendMessageClientImpl.class); 19 | 20 | private static final String WS_URI = "ws://localhost:8012/reverse"; 21 | 22 | @Override 23 | public void process() { 24 | 25 | BlockchainWebSocketHandler handler = new BlockchainWebSocketHandler(); 26 | WebSocketClient client = new StandardWebSocketClient(); 27 | try { 28 | WebSocketSession session = client.doHandshake(handler, WS_URI).get(); 29 | session.sendMessage(new TextMessage("Hello World test.")); 30 | session.close(); 31 | } catch (Exception e) { 32 | logger.info(e); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/danieljyc/websocket/server/BlockchainWebSocket.java: -------------------------------------------------------------------------------- 1 | 2 | package com.danieljyc.websocket.server; 3 | 4 | import org.apache.commons.logging.Log; 5 | import org.apache.commons.logging.LogFactory; 6 | import org.springframework.stereotype.Component; 7 | 8 | import javax.websocket.*; 9 | import javax.websocket.server.ServerEndpoint; 10 | import java.io.IOException; 11 | import java.util.concurrent.CopyOnWriteArraySet; 12 | import java.util.concurrent.atomic.AtomicLong; 13 | 14 | @Component 15 | @ServerEndpoint("/blockchain") 16 | public class BlockchainWebSocket { 17 | private Log logger = LogFactory.getLog(BlockchainWebSocket.class); 18 | 19 | /** 20 | * 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。 21 | */ 22 | private static AtomicLong onlineCount = new AtomicLong(0); 23 | 24 | /** 25 | * concurrent包的线程安全Set,用来存放每个客户端对应的BlockchainWebSocket对象。 26 | */ 27 | private static CopyOnWriteArraySet webSocketSet = new CopyOnWriteArraySet(); 28 | 29 | /** 30 | * 与某个客户端的连接会话,需要通过它来给客户端发送数据 31 | */ 32 | private Session session; 33 | 34 | 35 | /** 36 | * 收到客户端消息后调用的方法 37 | */ 38 | @OnMessage 39 | public void handleMessage(Session session, String message) { 40 | logger.info("Received msg: " + message); 41 | String sendMsg = "Reversed: " + new StringBuilder(message).reverse(); 42 | try { 43 | session.getBasicRemote().sendText(sendMsg); 44 | } catch (IOException e) { 45 | logger.error("Send message error. Message: " + sendMsg); 46 | } 47 | logger.info("Send message: " + sendMsg); 48 | } 49 | 50 | /** 51 | * 连接建立成功调用的方法 52 | */ 53 | @OnOpen 54 | public void onOpenWs(Session session) { 55 | this.session = session; 56 | webSocketSet.add(this); 57 | // 在线数加1 58 | incrementOnlinePeer(); 59 | System.out.println("有新连接加入!当前连接数为:" + getOnlinePeers()); 60 | } 61 | 62 | /** 63 | * 连接关闭调用的方法 64 | */ 65 | @OnClose 66 | public void onCloseWs() { 67 | //从set中删除 68 | webSocketSet.remove(this); 69 | decrementOnlinePeer(); 70 | logger.info("有一连接关闭!当前连接数为" + getOnlinePeers()); 71 | } 72 | 73 | @OnError 74 | public void onErrorWs(Session session, Throwable error) { 75 | logger.info(String.format("Session %s,OnError: %s", session, error)); 76 | } 77 | 78 | 79 | /** 80 | * 发送消息 message 81 | */ 82 | private void sendMessage(String message) { 83 | try { 84 | session.getBasicRemote().sendText(message); 85 | } catch (IOException e) { 86 | logger.error("Send error.", e); 87 | } 88 | } 89 | 90 | /** 91 | * 广播 92 | */ 93 | public static void sendMessageToAllPeers(String message) throws IOException { 94 | for (BlockchainWebSocket item : webSocketSet) { 95 | item.sendMessage(message); 96 | } 97 | } 98 | 99 | /** 100 | * 获取当前连接数 101 | */ 102 | private static synchronized long getOnlinePeers() { 103 | return onlineCount.longValue(); 104 | } 105 | 106 | /** 107 | * 当前连接数 +1 108 | */ 109 | private static synchronized void incrementOnlinePeer() { 110 | onlineCount.incrementAndGet(); 111 | } 112 | 113 | /** 114 | * 当前连接数 -1 115 | */ 116 | private static synchronized void decrementOnlinePeer() { 117 | onlineCount.decrementAndGet(); 118 | } 119 | 120 | @Override 121 | public int hashCode() { 122 | return super.hashCode(); 123 | } 124 | 125 | @Override 126 | public boolean equals(Object obj) { 127 | return super.equals(obj); 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /src/main/java/com/danieljyc/websocket/server/reverse/ReverseWebSocketEndpoint.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012-2015 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.danieljyc.websocket.server.reverse; 18 | 19 | import org.apache.commons.logging.Log; 20 | import org.apache.commons.logging.LogFactory; 21 | import org.springframework.stereotype.Component; 22 | 23 | import javax.websocket.OnMessage; 24 | import javax.websocket.Session; 25 | import javax.websocket.server.ServerEndpoint; 26 | import java.io.IOException; 27 | 28 | @Component 29 | @ServerEndpoint("/reverse") 30 | public class ReverseWebSocketEndpoint { 31 | private Log logger = LogFactory.getLog(ReverseWebSocketEndpoint.class); 32 | 33 | @OnMessage 34 | public void handleMessage(Session session, String message) throws IOException { 35 | logger.info("Received msg: " + message); 36 | String sendMsg = "Reversed: " + new StringBuilder(message).reverse(); 37 | session.getBasicRemote().sendText(sendMsg); 38 | logger.info("Send msg: " + sendMsg); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | com.dudu.name=daniel 2 | com.dudu.want=jyc 3 | server.port=8012 -------------------------------------------------------------------------------- /src/test/java/com/danieljyc/BitcoinApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.danieljyc; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class BitcoinApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | --------------------------------------------------------------------------------