├── .gitignore ├── LICENSE ├── jmFuncs ├── .project ├── .settings │ ├── org.eclipse.jdt.core.prefs │ └── org.eclipse.m2e.core.prefs ├── pom.xml └── src │ └── main │ └── java │ └── net │ └── xmeter │ └── functions │ └── MyRandomFunc.java ├── jmeter_Jenkins ├── build.xml ├── lib │ └── ant-jmeter-1.1.1.jar └── test.jmx ├── jmx ├── account.txt ├── sample.jmx ├── session2.jmx └── tc_case.jmx ├── my-jmeter-plugins-demo ├── pom.xml └── src │ └── main │ └── java │ └── my │ └── jmeter │ ├── functions │ ├── IntSum.java │ └── MyAverageFunction.java │ ├── gui │ └── MySimpleSamplerGui.java │ └── samplers │ ├── MyJavaSamplerDemo.java │ └── MySimpleSampler.java ├── socket_echo ├── .classpath ├── .project ├── .settings │ ├── org.eclipse.core.resources.prefs │ ├── org.eclipse.jdt.core.prefs │ └── org.eclipse.m2e.core.prefs ├── pom.xml └── src │ ├── main │ └── java │ │ └── net │ │ └── xmeter │ │ └── echo │ │ ├── BinaryClient.java │ │ ├── BinaryServer.java │ │ ├── Constants.java │ │ └── TextServer.java │ └── test │ └── java │ └── net │ └── xmeter │ └── socket_echo │ └── AppTest.java ├── tcp └── src │ └── protocol │ └── tcp │ └── org │ └── apache │ └── jmeter │ └── protocol │ └── tcp │ ├── config │ └── gui │ │ └── TCPConfigGui.java │ ├── control │ └── gui │ │ └── TCPSamplerGui.java │ └── sampler │ ├── AbstractTCPClient.java │ ├── BinaryTCPClientImpl.java │ ├── LengthPrefixedBinaryTCPClientImpl.java │ ├── ReadException.java │ ├── TCPClient.java │ ├── TCPClientDecorator.java │ ├── TCPClientImpl.java │ └── TCPSampler.java └── wsocket_echo ├── .settings ├── .jsdtscope ├── org.eclipse.core.resources.prefs ├── org.eclipse.jdt.core.prefs ├── org.eclipse.m2e.core.prefs ├── org.eclipse.wst.common.component ├── org.eclipse.wst.jsdt.ui.superType.container ├── org.eclipse.wst.jsdt.ui.superType.name └── org.eclipse.wst.validation.prefs ├── main └── java │ └── net │ └── xmeter │ └── EchoService.java ├── pom.xml └── src └── main └── webapp ├── WEB-INF └── web.xml ├── css └── starter-template.css └── wsocket_client.html /.gitignore: -------------------------------------------------------------------------------- 1 | ..classpath.icloud 2 | ..project.icloud 3 | .classpath 4 | .project 5 | .settings/ 6 | target/ 7 | .idea/ 8 | .metadata/ 9 | .recommenders/ 10 | *.iml 11 | **/build/ 12 | .gradle 13 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /jmFuncs/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | jmFuncs 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.eclipse.m2e.core.maven2Builder 15 | 16 | 17 | 18 | 19 | 20 | org.eclipse.jdt.core.javanature 21 | org.eclipse.m2e.core.maven2Nature 22 | 23 | 24 | -------------------------------------------------------------------------------- /jmFuncs/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 3 | org.eclipse.jdt.core.compiler.compliance=1.5 4 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning 5 | org.eclipse.jdt.core.compiler.source=1.5 6 | -------------------------------------------------------------------------------- /jmFuncs/.settings/org.eclipse.m2e.core.prefs: -------------------------------------------------------------------------------- 1 | activeProfiles= 2 | eclipse.preferences.version=1 3 | resolveWorkspaceProjects=true 4 | version=1 5 | -------------------------------------------------------------------------------- /jmFuncs/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | net.xmeter 4 | jmFuncs 5 | 0.0.1-SNAPSHOT 6 | 7 | 8 | org.apache.jmeter 9 | ApacheJMeter_core 10 | 3.0 11 | 12 | 13 | org.apache.jmeter 14 | ApacheJMeter_functions 15 | 3.0 16 | 17 | 18 | -------------------------------------------------------------------------------- /jmFuncs/src/main/java/net/xmeter/functions/MyRandomFunc.java: -------------------------------------------------------------------------------- 1 | package net.xmeter.functions; 2 | 3 | import java.security.SecureRandom; 4 | import java.util.Collection; 5 | import java.util.LinkedList; 6 | import java.util.List; 7 | 8 | import org.apache.jmeter.engine.util.CompoundVariable; 9 | import org.apache.jmeter.functions.AbstractFunction; 10 | import org.apache.jmeter.functions.InvalidVariableException; 11 | import org.apache.jmeter.samplers.SampleResult; 12 | import org.apache.jmeter.samplers.Sampler; 13 | 14 | public class MyRandomFunc extends AbstractFunction{ 15 | //自定义function的描述 16 | private static final List desc = new LinkedList(); 17 | static { 18 | desc.add("Get a random result string."); 19 | } 20 | //function名称 21 | private static final String KEY = "__MyRandomFunc"; 22 | 23 | private SecureRandom random = new SecureRandom(); 24 | private static char[] seeds = "abcdefghijklmnopqrstuvwxmy0123456789".toCharArray(); 25 | 26 | public List getArgumentDesc() { 27 | return desc; 28 | } 29 | 30 | @Override 31 | public String execute(SampleResult arg0, Sampler arg1) throws InvalidVariableException { 32 | StringBuffer res = new StringBuffer(); 33 | for(int i = 0; i < 1024; i++) { 34 | res.append(seeds[random.nextInt(seeds.length - 1)]); 35 | } 36 | return res.toString(); 37 | } 38 | 39 | @Override 40 | public String getReferenceKey() { 41 | return KEY; 42 | } 43 | 44 | @Override 45 | public void setParameters(Collection arg0) throws InvalidVariableException { 46 | 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /jmeter_Jenkins/build.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /jmeter_Jenkins/lib/ant-jmeter-1.1.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XMeterSaaSService/Blog_sample_project/1578d32dbd854d775bc98253f61eece8d4959485/jmeter_Jenkins/lib/ant-jmeter-1.1.1.jar -------------------------------------------------------------------------------- /jmeter_Jenkins/test.jmx: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | false 7 | false 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | continue 16 | 17 | false 18 | 10 19 | 20 | 10 21 | 1 22 | 1477407398000 23 | 1477407398000 24 | false 25 | 26 | 27 | 28 | 29 | 30 | true 31 | true 32 | 200 33 | OK 34 | hello 35 | world 36 | ${__Random(50,500)} 37 | ${__Random(1,50)} 38 | ${__Random(1,5)} 39 | 40 | 41 | 42 | 43 | 44 | 45 | www.baidu.com 46 | 47 | 48 | 49 | 50 | 51 | 52 | GET 53 | true 54 | false 55 | true 56 | false 57 | false 58 | 59 | 60 | 61 | 62 | false 63 | true 64 | true 65 | false 66 | 67 | 68 | 69 | 70 | world 71 | 72 | Assertion.response_data 73 | false 74 | 16 75 | 76 | 77 | 78 | false 79 | 80 | saveConfig 81 | 82 | 83 | true 84 | true 85 | true 86 | 87 | true 88 | true 89 | true 90 | true 91 | false 92 | true 93 | true 94 | false 95 | false 96 | false 97 | true 98 | false 99 | false 100 | false 101 | true 102 | 0 103 | true 104 | true 105 | true 106 | 107 | 108 | 109 | 110 | 111 | 112 | 300 113 | 114 | 115 | 116 | 117 | 118 | 119 | -------------------------------------------------------------------------------- /jmx/account.txt: -------------------------------------------------------------------------------- 1 | user1,password1 2 | user2,password2 3 | user3,password3 4 | user4,password4 5 | user5,password5 6 | user6,password6 7 | -------------------------------------------------------------------------------- /jmx/sample.jmx: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | false 7 | false 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | continue 16 | 17 | false 18 | -1 19 | 20 | 3 21 | 1 22 | 1474814506000 23 | 1474814506000 24 | false 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | www.YourCompany.com 34 | 35 | 36 | 37 | http 38 | 39 | / 40 | GET 41 | true 42 | false 43 | true 44 | false 45 | HttpClient4 46 | false 47 | 48 | 请将www.YourCompany.com换成您的待测网站! 不必带上http(s)://前缀. Path为网站域名后面的URI, 比如/ 或者 /mypage.html 49 | 50 | 51 | 52 | 53 | 54 | Accept-Language 55 | en-US,zh-CN;q=0.8,en;q=0.5,zh;q=0.3 56 | 57 | 58 | Upgrade-Insecure-Requests 59 | 1 60 | 61 | 62 | Accept-Encoding 63 | gzip, deflate 64 | 65 | 66 | User-Agent 67 | Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:48.0) Gecko/20100101 Firefox/48.0 68 | 69 | 70 | Accept 71 | text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 72 | 73 | 74 | 75 | 76 | 77 | 300 78 | 79 | 80 | 81 | 82 | false 83 | 84 | saveConfig 85 | 86 | 87 | true 88 | true 89 | true 90 | 91 | true 92 | true 93 | true 94 | true 95 | false 96 | true 97 | true 98 | true 99 | false 100 | false 101 | true 102 | false 103 | false 104 | false 105 | true 106 | 0 107 | true 108 | true 109 | true 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | -------------------------------------------------------------------------------- /jmx/session2.jmx: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | false 7 | false 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | continue 16 | 17 | false 18 | 5 19 | 20 | 1 21 | 1 22 | 1522051247000 23 | 1522051247000 24 | false 25 | 26 | 27 | 28 | 29 | 30 | true 31 | true 32 | 200 33 | OK 34 | {"email":"${email}", "password":"${password}"} 35 | {"successful": true, "account_id":"0123456789"} 36 | ${__Random(50,500)} 37 | ${__Random(1,50)} 38 | ${__Random(1,5)} 39 | 40 | 41 | 42 | , 43 | 44 | account.txt 45 | false 46 | false 47 | true 48 | shareMode.all 49 | false 50 | email,password 51 | 52 | 53 | 54 | 55 | true 56 | 57 | Assertion.response_data 58 | false 59 | 2 60 | 61 | 62 | 63 | false 64 | account_id 65 | "account_id":"(.+?)" 66 | $1$ 67 | 68 | 69 | 70 | 71 | 72 | 73 | true 74 | true 75 | 200 76 | OK 77 | ${account_id} 78 | {"account_name": "test", "account_id":"${account_id}", "name":"zhangsan"} 79 | ${__Random(50,500)} 80 | ${__Random(1,50)} 81 | ${__Random(1,5)} 82 | 83 | 84 | 85 | false 86 | 87 | saveConfig 88 | 89 | 90 | true 91 | true 92 | true 93 | 94 | true 95 | true 96 | true 97 | true 98 | false 99 | true 100 | true 101 | false 102 | false 103 | false 104 | true 105 | false 106 | false 107 | false 108 | true 109 | 0 110 | true 111 | true 112 | true 113 | true 114 | true 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | true 124 | 125 | 126 | 127 | 128 | -------------------------------------------------------------------------------- /jmx/tc_case.jmx: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | continue 6 | 7 | false 8 | 1 9 | 10 | 1 11 | 1 12 | 1478264923000 13 | 1478264923000 14 | false 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | www.baidu.com 24 | 25 | 26 | 27 | 28 | 29 | 30 | GET 31 | true 32 | false 33 | true 34 | false 35 | false 36 | 37 | 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /my-jmeter-plugins-demo/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | my.jmeter 4 | my-jmeter-plugins-demo 5 | 0.0.1-SNAPSHOT 6 | 7 | 8 | 9 | org.apache.jmeter 10 | ApacheJMeter_core 11 | 4.0 12 | provided 13 | 14 | 15 | org.apache.jmeter 16 | ApacheJMeter_java 17 | 4.0 18 | provided 19 | 20 | 21 | 22 | 23 | my-jmeter-plugins-${project.version} 24 | 25 | 26 | org.apache.maven.plugins 27 | maven-compiler-plugin 28 | 3.8.0 29 | 30 | 1.8 31 | 1.8 32 | 33 | 34 | 35 | org.apache.maven.plugins 36 | maven-assembly-plugin 37 | 38 | 39 | 40 | jar-with-dependencies 41 | 42 | 43 | 44 | 45 | assemble-all 46 | package 47 | 48 | single 49 | 50 | 51 | 52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /my-jmeter-plugins-demo/src/main/java/my/jmeter/functions/IntSum.java: -------------------------------------------------------------------------------- 1 | package my.jmeter.functions; 2 | 3 | import java.util.Collection; 4 | import java.util.LinkedList; 5 | import java.util.List; 6 | 7 | import org.apache.jmeter.engine.util.CompoundVariable; 8 | import org.apache.jmeter.functions.AbstractFunction; 9 | import org.apache.jmeter.functions.InvalidVariableException; 10 | import org.apache.jmeter.samplers.SampleResult; 11 | import org.apache.jmeter.samplers.Sampler; 12 | import org.apache.jmeter.threads.JMeterVariables; 13 | 14 | public class IntSum extends AbstractFunction { 15 | 16 | private static final String KEY = "__intSum"; 17 | 18 | private static final List desc = new LinkedList<>(); 19 | 20 | static { 21 | desc.add("第一个整数"); 22 | desc.add("第二个整数(通过添加更多的参数来增加更多的整数)"); 23 | desc.add("存储结果的变量名(可选)"); 24 | } 25 | 26 | private Object[] values; 27 | 28 | @Override 29 | public List getArgumentDesc() { 30 | return desc; 31 | } 32 | 33 | @Override 34 | public String execute(SampleResult previousResult, Sampler currentSampler) throws InvalidVariableException { 35 | int sum = 0; 36 | String varName = ((CompoundVariable) values[values.length - 1]).execute().trim(); 37 | 38 | //对除最后一个参数外的其他参数求和 39 | for (int i = 0; i < values.length - 1; i++) { 40 | sum += Integer.parseInt(((CompoundVariable) values[i]).execute()); 41 | } 42 | 43 | //处理最后一个参数 44 | try { 45 | sum += Integer.parseInt(varName); //最后一个参数仍为整数,加入求和结果 46 | varName = null; // there is no variable name 47 | } catch(NumberFormatException ignored) { 48 | // varName keeps its value and sum has not taken 49 | // into account non numeric or overflowing number 50 | } 51 | 52 | String totalString = Integer.toString(sum); 53 | //最后一个参数为变量名,保存为JMeter的变量 54 | JMeterVariables vars = getVariables(); 55 | if (vars != null && varName != null){// vars will be null on TestPlan 56 | vars.put(varName.trim(), totalString); 57 | } 58 | 59 | return totalString; 60 | } 61 | 62 | @Override 63 | public void setParameters(Collection parameters) throws InvalidVariableException { 64 | checkMinParameterCount(parameters, 2); //求和至少需要2个参数 65 | values = parameters.toArray(); 66 | } 67 | 68 | @Override 69 | public String getReferenceKey() { 70 | return KEY; 71 | } 72 | 73 | } 74 | -------------------------------------------------------------------------------- /my-jmeter-plugins-demo/src/main/java/my/jmeter/functions/MyAverageFunction.java: -------------------------------------------------------------------------------- 1 | package my.jmeter.functions; 2 | 3 | import java.util.Collection; 4 | import java.util.LinkedList; 5 | import java.util.List; 6 | 7 | import org.apache.jmeter.engine.util.CompoundVariable; 8 | import org.apache.jmeter.functions.AbstractFunction; 9 | import org.apache.jmeter.functions.InvalidVariableException; 10 | import org.apache.jmeter.samplers.SampleResult; 11 | import org.apache.jmeter.samplers.Sampler; 12 | import org.apache.jmeter.threads.JMeterVariables; 13 | 14 | public class MyAverageFunction extends AbstractFunction { 15 | 16 | private static final String KEY = "__myAverage"; 17 | 18 | private static final List desc = new LinkedList<>(); 19 | 20 | static { 21 | desc.add("第一个整数"); 22 | desc.add("第二个整数(通过添加更多的参数来增加更多的整数)"); 23 | desc.add("存储结果的变量名(可选)"); 24 | } 25 | 26 | private Object[] values; 27 | 28 | @Override 29 | public List getArgumentDesc() { 30 | return desc; 31 | } 32 | 33 | @Override 34 | public String execute(SampleResult previousResult, Sampler currentSampler) throws InvalidVariableException { 35 | int sum = 0; 36 | int count = 0; 37 | String varName = ((CompoundVariable) values[values.length - 1]).execute().trim(); 38 | 39 | //对除最后一个参数外的其他参数求和 40 | for (int i = 0; i < values.length - 1; i++) { 41 | sum += Integer.parseInt(((CompoundVariable) values[i]).execute()); 42 | count++; 43 | } 44 | 45 | //处理最后一个参数 46 | try { 47 | sum += Integer.parseInt(varName); //最后一个参数仍为整数 48 | count++; 49 | varName = null; // there is no variable name 50 | } catch(NumberFormatException ignored) { 51 | // varName keeps its value and sum has not taken 52 | // into account non numeric or overflowing number 53 | } 54 | 55 | int avg = sum/count; 56 | String result = String.valueOf(avg); 57 | 58 | //最后一个参数为变量名,保存为JMeter的变量 59 | JMeterVariables vars = getVariables(); 60 | if (vars != null && varName != null){// vars will be null on TestPlan 61 | vars.put(varName.trim(), result); 62 | } 63 | 64 | return result; 65 | } 66 | 67 | @Override 68 | public void setParameters(Collection parameters) throws InvalidVariableException { 69 | checkMinParameterCount(parameters, 2); 70 | values = parameters.toArray(); 71 | } 72 | 73 | @Override 74 | public String getReferenceKey() { 75 | return KEY; 76 | } 77 | 78 | } 79 | -------------------------------------------------------------------------------- /my-jmeter-plugins-demo/src/main/java/my/jmeter/gui/MySimpleSamplerGui.java: -------------------------------------------------------------------------------- 1 | package my.jmeter.gui; 2 | 3 | import java.awt.BorderLayout; 4 | 5 | import javax.swing.JPanel; 6 | 7 | import org.apache.jmeter.samplers.gui.AbstractSamplerGui; 8 | import org.apache.jmeter.testelement.TestElement; 9 | import org.apache.jorphan.gui.JLabeledTextField; 10 | 11 | import my.jmeter.samplers.MySimpleSampler; 12 | 13 | public class MySimpleSamplerGui extends AbstractSamplerGui { 14 | 15 | /** 16 | * 17 | */ 18 | private static final long serialVersionUID = 124L; 19 | 20 | private JLabeledTextField nameField = new JLabeledTextField("Input your name: "); 21 | private static final String DEFAULT_NAME = "World"; 22 | 23 | public MySimpleSamplerGui() { 24 | init(); 25 | } 26 | 27 | private void init() { 28 | setLayout(new BorderLayout()); 29 | setBorder(makeBorder()); 30 | 31 | add(makeTitlePanel(), BorderLayout.NORTH); 32 | JPanel mainPanel = new JPanel(); 33 | mainPanel.add(nameField); 34 | add(mainPanel, BorderLayout.CENTER); 35 | } 36 | 37 | @Override 38 | public String getLabelResource() { 39 | return null; 40 | } 41 | 42 | @Override 43 | public String getStaticLabel() { 44 | return "My Simple Sampler"; 45 | } 46 | 47 | //新生成的GUI从TestElement中获取数据 48 | @Override 49 | public void configure(TestElement element) { 50 | super.configure(element); 51 | MySimpleSampler sampler = (MySimpleSampler) element; 52 | nameField.setText(sampler.getInputName()); 53 | } 54 | 55 | //在GUI组件中生成TestElement的时候,将数据从GUI传递给TestElement 56 | @Override 57 | public TestElement createTestElement() { 58 | MySimpleSampler element = new MySimpleSampler(); 59 | modifyTestElement(element); 60 | return element; 61 | } 62 | 63 | //给TestElement设置值 64 | @Override 65 | public void modifyTestElement(TestElement element) { 66 | MySimpleSampler sampler = (MySimpleSampler) element; 67 | sampler.setInputName(nameField.getText()); 68 | super.configureTestElement(sampler); //This method will set the name, gui class, and test class for the created Test Element 69 | } 70 | 71 | //重置 72 | @Override 73 | public void clearGui() { 74 | super.clearGui(); 75 | nameField.setText(DEFAULT_NAME); 76 | } 77 | 78 | } 79 | -------------------------------------------------------------------------------- /my-jmeter-plugins-demo/src/main/java/my/jmeter/samplers/MyJavaSamplerDemo.java: -------------------------------------------------------------------------------- 1 | package my.jmeter.samplers; 2 | 3 | import org.apache.jmeter.config.Arguments; 4 | import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient; 5 | import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext; 6 | import org.apache.jmeter.samplers.SampleResult; 7 | 8 | public class MyJavaSamplerDemo extends AbstractJavaSamplerClient { 9 | 10 | @Override 11 | public SampleResult runTest(JavaSamplerContext context) { 12 | SampleResult result = new SampleResult(); 13 | result.sampleStart(); 14 | 15 | //business logic... 16 | String name = context.getParameter("Name"); 17 | result.setSamplerData("Could you say hello to me? My name is " + name + "."); 18 | 19 | result.sampleEnd(); 20 | 21 | //这里将Name参数值写入response中 22 | result.setSuccessful(true); 23 | String message = "Hello, " + name + "!"; 24 | result.setResponseMessage("This is response message: " + message); 25 | result.setResponseData(new String("This is response data: " + message).getBytes()); 26 | result.setResponseCodeOK(); 27 | return result; 28 | } 29 | 30 | @Override 31 | public Arguments getDefaultParameters() { 32 | Arguments arguments = new Arguments(); 33 | arguments.addArgument("Name", "World"); 34 | return arguments; 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /my-jmeter-plugins-demo/src/main/java/my/jmeter/samplers/MySimpleSampler.java: -------------------------------------------------------------------------------- 1 | package my.jmeter.samplers; 2 | 3 | import org.apache.jmeter.samplers.AbstractSampler; 4 | import org.apache.jmeter.samplers.Entry; 5 | import org.apache.jmeter.samplers.SampleResult; 6 | 7 | public class MySimpleSampler extends AbstractSampler { 8 | 9 | /** 10 | * 11 | */ 12 | private static final long serialVersionUID = 123L; 13 | 14 | private static final String MY_SAMPLE_NAME = "MySimpleSampler.name"; //对应脚本中的property 15 | 16 | @Override 17 | public SampleResult sample(Entry e) { 18 | SampleResult result = new SampleResult(); 19 | result.setSampleLabel(getName()); 20 | String name = getInputName(); 21 | 22 | result.sampleStart(); 23 | result.setSamplerData("Could you say hello to me? My name is " + name + "."); 24 | 25 | result.sampleEnd(); 26 | result.setSuccessful(true); 27 | String message = "Hello, " + name + "!"; 28 | result.setResponseMessage("This is response message: " + message); 29 | result.setResponseData(new String("This is response data: " + message).getBytes()); 30 | result.setResponseCodeOK(); 31 | return result; 32 | } 33 | 34 | public String getInputName() { 35 | return this.getPropertyAsString(MY_SAMPLE_NAME); 36 | } 37 | 38 | public void setInputName(String name) { 39 | this.setProperty(MY_SAMPLE_NAME, name); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /socket_echo/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /socket_echo/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | socket_echo 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.eclipse.m2e.core.maven2Builder 15 | 16 | 17 | 18 | 19 | 20 | org.eclipse.jdt.core.javanature 21 | org.eclipse.m2e.core.maven2Nature 22 | 23 | 24 | -------------------------------------------------------------------------------- /socket_echo/.settings/org.eclipse.core.resources.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | encoding//src/main/java=UTF-8 3 | encoding//src/test/java=UTF-8 4 | encoding/=UTF-8 5 | -------------------------------------------------------------------------------- /socket_echo/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 3 | org.eclipse.jdt.core.compiler.compliance=1.7 4 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning 5 | org.eclipse.jdt.core.compiler.source=1.7 6 | -------------------------------------------------------------------------------- /socket_echo/.settings/org.eclipse.m2e.core.prefs: -------------------------------------------------------------------------------- 1 | activeProfiles= 2 | eclipse.preferences.version=1 3 | resolveWorkspaceProjects=true 4 | version=1 5 | -------------------------------------------------------------------------------- /socket_echo/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.xmeter 8 | xmeter-parent 9 | 0.0.3-SNAPSHOT 10 | 11 | net.xmeter 12 | socket_echo 13 | 0.0.1-SNAPSHOT 14 | socket_echo 15 | http://maven.apache.org 16 | 17 | UTF-8 18 | 19 | 20 | 21 | junit 22 | junit 23 | 3.8.1 24 | test 25 | 26 | 27 | 28 | 29 | 30 | org.apache.maven.plugins 31 | maven-compiler-plugin 32 | 3.2 33 | 34 | 1.7 35 | 1.7 36 | 37 | 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /socket_echo/src/main/java/net/xmeter/echo/BinaryClient.java: -------------------------------------------------------------------------------- 1 | package net.xmeter.echo; 2 | 3 | import java.io.InputStream; 4 | import java.io.OutputStream; 5 | import java.net.InetAddress; 6 | import java.net.Socket; 7 | import java.util.concurrent.TimeUnit; 8 | 9 | public class BinaryClient implements Constants{ 10 | private static byte[] produceData() { 11 | byte[] data = new byte[]{START_DELIMITER, 0x3, TYPE_TEMPERATURE, 1, TYPE_BRIGHTNESS, 20, TYPE_HUMIDITY, 30}; 12 | long checksum = BinaryServer.calculateChecksum(data); 13 | byte[] ret = new byte[data.length + 1]; 14 | System.arraycopy(data, 0, ret, 0, data.length); 15 | ret[ret.length - 1] = (byte) checksum; 16 | System.out.println(bytesToHex(ret)); 17 | return ret; 18 | } 19 | 20 | final protected static char[] hexArray = "0123456789ABCDEF".toCharArray(); 21 | public static String bytesToHex(byte[] bytes) { 22 | char[] hexChars = new char[bytes.length * 2]; 23 | for ( int j = 0; j < bytes.length; j++ ) { 24 | int v = bytes[j] & 0xFF; 25 | hexChars[j * 2] = hexArray[v >>> 4]; 26 | hexChars[j * 2 + 1] = hexArray[v & 0x0F]; 27 | } 28 | return new String(hexChars); 29 | } 30 | 31 | 32 | public static void main(String[] args) throws Exception { 33 | Socket server; 34 | server = new Socket(InetAddress.getLocalHost(), 4700); 35 | InputStream stream = server.getInputStream(); 36 | OutputStream os = server.getOutputStream(); 37 | int count = 0; 38 | while (true) { 39 | if(count == 3) { 40 | break; 41 | } 42 | os.write(produceData()); 43 | os.flush(); 44 | byte[] data = new byte[2014]; 45 | int length = stream.read(data); 46 | if(length != -1) { 47 | byte[] tmp = new byte[length - 2]; 48 | System.arraycopy(data, 0, tmp, 0, length - 2); 49 | System.out.println(bytesToHex(tmp)); 50 | } 51 | TimeUnit.SECONDS.sleep(1); 52 | count++; 53 | } 54 | server.close(); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /socket_echo/src/main/java/net/xmeter/echo/BinaryServer.java: -------------------------------------------------------------------------------- 1 | package net.xmeter.echo; 2 | 3 | import java.io.DataInputStream; 4 | import java.io.IOException; 5 | import java.io.OutputStream; 6 | import java.net.ServerSocket; 7 | import java.net.Socket; 8 | import java.text.MessageFormat; 9 | import java.util.concurrent.ExecutorService; 10 | import java.util.concurrent.Executors; 11 | import java.util.concurrent.TimeUnit; 12 | import java.util.concurrent.atomic.AtomicInteger; 13 | 14 | class SensorData { 15 | int type; 16 | int value; 17 | } 18 | 19 | public class BinaryServer implements Constants { 20 | public static AtomicInteger sessions = new AtomicInteger(0); 21 | 22 | public void handleRequest(final Socket socket) { 23 | ExecutorService executor = Executors.newSingleThreadExecutor(); 24 | 25 | executor.submit(new Runnable() { 26 | @Override 27 | public void run() { 28 | try { 29 | DataInputStream ds = new DataInputStream(socket.getInputStream()); 30 | OutputStream os = socket.getOutputStream(); 31 | int readEmptyContentCount = 0; 32 | while (true) { 33 | byte[] data = new byte[1024]; 34 | int actualLen = ds.read(data); 35 | if (actualLen == -1) { 36 | TimeUnit.MICROSECONDS.sleep(100); 37 | readEmptyContentCount++; 38 | if(readEmptyContentCount == 50) { 39 | System.out.println("Probably the client side closed the connection, now close me as well."); 40 | socket.close(); 41 | break; 42 | } 43 | continue; 44 | } 45 | byte[] tmp = new byte[actualLen]; 46 | System.arraycopy(data, 0, tmp, 0, actualLen); 47 | int startDelimterIndex = -1; 48 | for (int i = 0; i < tmp.length; i++) { 49 | if (tmp[i] == START_DELIMITER) { 50 | startDelimterIndex = i; 51 | break; 52 | } 53 | } 54 | if (startDelimterIndex != -1) { 55 | System.out.println("Find the start delimiter at " + startDelimterIndex + "."); 56 | byte[] ret = parseData(startDelimterIndex, tmp); 57 | os.write(ret); 58 | os.flush(); 59 | } 60 | } 61 | } catch (Exception ex) { 62 | ex.printStackTrace(); 63 | } finally { 64 | try { 65 | socket.close(); 66 | int num = sessions.decrementAndGet(); 67 | System.out.println("Now has " + num + " of conn."); 68 | } catch (IOException e) { 69 | e.printStackTrace(); 70 | } 71 | } 72 | } 73 | 74 | }); 75 | } 76 | 77 | public static long calculateChecksum(byte[] buf) { 78 | int length = buf.length; 79 | int i = 0; 80 | 81 | long sum = 0; 82 | long data; 83 | 84 | // Handle all pairs 85 | while (length > 1) { 86 | data = (((buf[i] << 8) & 0xFF00) | ((buf[i + 1]) & 0xFF)); 87 | sum += data; 88 | if ((sum & 0xFFFF0000) > 0) { 89 | sum = sum & 0xFFFF; 90 | sum += 1; 91 | } 92 | 93 | i += 2; 94 | length -= 2; 95 | } 96 | 97 | if (length > 0) { 98 | sum += (buf[i] << 8 & 0xFF00); 99 | if ((sum & 0xFFFF0000) > 0) { 100 | sum = sum & 0xFFFF; 101 | sum += 1; 102 | } 103 | } 104 | 105 | sum = ~sum; 106 | sum = sum & 0xFFFF; 107 | return sum; 108 | } 109 | 110 | /** 111 | * The protocol: start_delimit|length[|data_type|data_val]|checksum 112 | */ 113 | private byte[] parseData(int startDelimiter, byte[] data) { 114 | if (!validateChecksum(startDelimiter, data)) { 115 | long checksum = calculateChecksum(new byte[] {START_DELIMITER, RESPONSE_ERR}); 116 | System.out.println("Wrong data, invalid checksum. Return with err response code."); 117 | return new byte[] {START_DELIMITER, RESPONSE_ERR, (byte)checksum, '\n'}; 118 | } 119 | 120 | int length = data[startDelimiter + 1]; 121 | if(length == 0) { 122 | long checksum = calculateChecksum(new byte[] {START_DELIMITER, RESPONSE_ERR}); 123 | System.out.println("Wrong data, invalid data length. Return with err response code."); 124 | return new byte[] {START_DELIMITER, RESPONSE_ERR, (byte)checksum, '\n'}; 125 | } 126 | 127 | int dataCount = 0; 128 | for (int i = 2; i < data.length;) { 129 | int type = data[i++]; 130 | int value = data[i++]; 131 | dumpData(type, value); 132 | dataCount++; 133 | if(length == dataCount) { 134 | break; 135 | } 136 | } 137 | long checksum = calculateChecksum(new byte[] {START_DELIMITER, RESPONSE_OK}); 138 | System.out.println("Correct data. Return with correct response code."); 139 | return new byte[] {START_DELIMITER, RESPONSE_OK, (byte)checksum, '\n'}; 140 | } 141 | 142 | private void dumpData(int type, int data) { 143 | String desc = "Unknow type"; 144 | if (type == TYPE_BRIGHTNESS) { 145 | desc = "brightness"; 146 | } else if (type == TYPE_HUMIDITY) { 147 | desc = "humidity"; 148 | } else if (type == TYPE_TEMPERATURE) { 149 | desc = "temperature"; 150 | } 151 | System.out.println(MessageFormat.format("Received data {0} for sensor {1}.", data, desc)); 152 | } 153 | 154 | private boolean validateChecksum(int startDelimiter, byte[] data) { 155 | byte[] tmp = new byte[data.length - 1]; 156 | System.arraycopy(data, 0, tmp, 0, data.length - 1); 157 | byte checksum = (byte) calculateChecksum(tmp); 158 | return checksum == data[data.length - 1]; 159 | } 160 | 161 | public static void main(String[] args) { 162 | try { 163 | ServerSocket server = new ServerSocket(4700); 164 | while (true) { 165 | Socket socket = server.accept(); 166 | BinaryServer srv = new BinaryServer(); 167 | srv.handleRequest(socket); 168 | int num = sessions.incrementAndGet(); 169 | System.out.println("Received new conn, now totally has " + num + " of conn."); 170 | } 171 | } catch (Exception e) { 172 | e.printStackTrace(); 173 | } 174 | } 175 | } 176 | -------------------------------------------------------------------------------- /socket_echo/src/main/java/net/xmeter/echo/Constants.java: -------------------------------------------------------------------------------- 1 | package net.xmeter.echo; 2 | 3 | public interface Constants { 4 | public static final int START_DELIMITER = 0x7e; 5 | public static final int TYPE_TEMPERATURE = 0x1; 6 | public static final int TYPE_BRIGHTNESS = 0x2; 7 | public static final int TYPE_HUMIDITY = 0x3; 8 | 9 | public static final int RESPONSE_OK = 0x00; 10 | public static final int RESPONSE_ERR = 0x01; 11 | } 12 | -------------------------------------------------------------------------------- /socket_echo/src/main/java/net/xmeter/echo/TextServer.java: -------------------------------------------------------------------------------- 1 | package net.xmeter.echo; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.InputStreamReader; 6 | import java.io.PrintWriter; 7 | import java.net.ServerSocket; 8 | import java.net.Socket; 9 | import java.util.concurrent.ExecutorService; 10 | import java.util.concurrent.Executors; 11 | import java.util.concurrent.atomic.AtomicInteger; 12 | 13 | public class TextServer { 14 | public static AtomicInteger sessions = new AtomicInteger(0); 15 | 16 | public void handleRequest(final Socket socket) { 17 | ExecutorService executor = Executors.newSingleThreadExecutor(); 18 | 19 | executor.submit(new Runnable() { 20 | @Override 21 | public void run() { 22 | try { 23 | BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream())); 24 | PrintWriter os = new PrintWriter(socket.getOutputStream()); 25 | while(true) { 26 | String line = is.readLine(); 27 | if(line == null) { 28 | System.out.println("Probably the client side closed the connection, now close me as well."); 29 | socket.close(); 30 | break; 31 | } 32 | System.out.println("Received message: " + line); 33 | os.println("Echo: " + line); 34 | os.flush(); 35 | if("bye".equals(line)) { 36 | break; 37 | } 38 | } 39 | } catch(Exception ex) { 40 | ex.printStackTrace(); 41 | } finally { 42 | try { 43 | socket.close(); 44 | int num = sessions.decrementAndGet(); 45 | System.out.println("Now totally has " + num + " of conn."); 46 | } catch (IOException e) { 47 | e.printStackTrace(); 48 | } 49 | } 50 | } 51 | 52 | }); 53 | 54 | } 55 | 56 | public static void main(String[] args) { 57 | try { 58 | ServerSocket server = new ServerSocket(4700); 59 | while(true) { 60 | Socket socket = server.accept(); 61 | TextServer srv = new TextServer(); 62 | srv.handleRequest(socket); 63 | int num = sessions.incrementAndGet(); 64 | System.out.println("Received new conn, now totally has " + num + " of conn."); 65 | } 66 | } catch (Exception e) { 67 | e.printStackTrace(); 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /socket_echo/src/test/java/net/xmeter/socket_echo/AppTest.java: -------------------------------------------------------------------------------- 1 | package net.xmeter.socket_echo; 2 | 3 | import junit.framework.Test; 4 | import junit.framework.TestCase; 5 | import junit.framework.TestSuite; 6 | 7 | /** 8 | * Unit test for simple App. 9 | */ 10 | public class AppTest 11 | extends TestCase 12 | { 13 | /** 14 | * Create the test case 15 | * 16 | * @param testName name of the test case 17 | */ 18 | public AppTest( String testName ) 19 | { 20 | super( testName ); 21 | } 22 | 23 | /** 24 | * @return the suite of tests being tested 25 | */ 26 | public static Test suite() 27 | { 28 | return new TestSuite( AppTest.class ); 29 | } 30 | 31 | /** 32 | * Rigourous Test :-) 33 | */ 34 | public void testApp() 35 | { 36 | assertTrue( true ); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /tcp/src/protocol/tcp/org/apache/jmeter/protocol/tcp/config/gui/TCPConfigGui.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | */ 18 | 19 | package org.apache.jmeter.protocol.tcp.config.gui; 20 | 21 | import java.awt.BorderLayout; 22 | import java.awt.Dimension; 23 | import java.awt.FlowLayout; 24 | import java.awt.event.ItemEvent; 25 | 26 | import javax.swing.BorderFactory; 27 | import javax.swing.JCheckBox; 28 | import javax.swing.JLabel; 29 | import javax.swing.JPanel; 30 | import javax.swing.JTextField; 31 | 32 | import org.apache.jmeter.config.ConfigTestElement; 33 | import org.apache.jmeter.config.gui.AbstractConfigGui; 34 | import org.apache.jmeter.gui.ServerPanel; 35 | import org.apache.jmeter.gui.util.HorizontalPanel; 36 | import org.apache.jmeter.gui.util.JSyntaxTextArea; 37 | import org.apache.jmeter.gui.util.JTextScrollPane; 38 | import org.apache.jmeter.gui.util.TristateCheckBox; 39 | import org.apache.jmeter.gui.util.VerticalPanel; 40 | import org.apache.jmeter.protocol.tcp.sampler.TCPSampler; 41 | import org.apache.jmeter.testelement.TestElement; 42 | import org.apache.jmeter.util.JMeterUtils; 43 | import org.apache.jorphan.gui.JLabeledTextField; 44 | 45 | public class TCPConfigGui extends AbstractConfigGui { 46 | 47 | private static final long serialVersionUID = 240L; 48 | 49 | private ServerPanel serverPanel; 50 | 51 | private JLabeledTextField classname; 52 | 53 | private JCheckBox reUseConnection; 54 | 55 | private TristateCheckBox setNoDelay; 56 | 57 | private TristateCheckBox closeConnection; 58 | 59 | private JTextField soLinger; 60 | 61 | private JTextField eolByte; 62 | 63 | private JTextField responseLenth; 64 | 65 | private JSyntaxTextArea requestData; 66 | 67 | private boolean displayName = true; 68 | 69 | public TCPConfigGui() { 70 | this(true); 71 | } 72 | 73 | public TCPConfigGui(boolean displayName) { 74 | this.displayName = displayName; 75 | init(); 76 | } 77 | 78 | @Override 79 | public String getLabelResource() { 80 | return "tcp_config_title"; // $NON-NLS-1$ 81 | } 82 | 83 | @Override 84 | public void configure(TestElement element) { 85 | super.configure(element); 86 | // N.B. this will be a config element, so we cannot use the getXXX() methods 87 | classname.setText(element.getPropertyAsString(TCPSampler.CLASSNAME)); 88 | serverPanel.setServer(element.getPropertyAsString(TCPSampler.SERVER)); 89 | // Default to original behaviour, i.e. re-use connection 90 | reUseConnection.setSelected(element.getPropertyAsBoolean(TCPSampler.RE_USE_CONNECTION, TCPSampler.RE_USE_CONNECTION_DEFAULT)); 91 | serverPanel.setPort(element.getPropertyAsString(TCPSampler.PORT)); 92 | serverPanel.setResponseTimeout(element.getPropertyAsString(TCPSampler.TIMEOUT)); 93 | serverPanel.setConnectTimeout(element.getPropertyAsString(TCPSampler.TIMEOUT_CONNECT)); 94 | setNoDelay.setTristateFromProperty(element, TCPSampler.NODELAY); 95 | requestData.setInitialText(element.getPropertyAsString(TCPSampler.REQUEST)); 96 | requestData.setCaretPosition(0); 97 | closeConnection.setTristateFromProperty(element, TCPSampler.CLOSE_CONNECTION); 98 | soLinger.setText(element.getPropertyAsString(TCPSampler.SO_LINGER)); 99 | eolByte.setText(element.getPropertyAsString(TCPSampler.EOL_BYTE)); 100 | responseLenth.setText(element.getPropertyAsString(TCPSampler.LENGTH, "")); 101 | } 102 | 103 | @Override 104 | public TestElement createTestElement() { 105 | ConfigTestElement element = new ConfigTestElement(); 106 | modifyTestElement(element); 107 | return element; 108 | } 109 | 110 | /** 111 | * Modifies a given TestElement to mirror the data in the gui components. 112 | * 113 | * @see org.apache.jmeter.gui.JMeterGUIComponent#modifyTestElement(TestElement) 114 | */ 115 | @Override 116 | public void modifyTestElement(TestElement element) { 117 | configureTestElement(element); 118 | // N.B. this will be a config element, so we cannot use the setXXX() methods 119 | element.setProperty(TCPSampler.CLASSNAME, classname.getText(), ""); 120 | element.setProperty(TCPSampler.SERVER, serverPanel.getServer()); 121 | element.setProperty(TCPSampler.RE_USE_CONNECTION, reUseConnection.isSelected()); 122 | element.setProperty(TCPSampler.PORT, serverPanel.getPort()); 123 | setNoDelay.setPropertyFromTristate(element, TCPSampler.NODELAY); 124 | element.setProperty(TCPSampler.TIMEOUT, serverPanel.getResponseTimeout()); 125 | element.setProperty(TCPSampler.TIMEOUT_CONNECT, serverPanel.getConnectTimeout(),""); 126 | element.setProperty(TCPSampler.REQUEST, requestData.getText()); 127 | closeConnection.setPropertyFromTristate(element, TCPSampler.CLOSE_CONNECTION); // Don't use default for saving tristates 128 | element.setProperty(TCPSampler.SO_LINGER, soLinger.getText(), ""); 129 | element.setProperty(TCPSampler.EOL_BYTE, eolByte.getText(), ""); 130 | element.setProperty(TCPSampler.LENGTH, responseLenth.getText(), ""); 131 | } 132 | 133 | /** 134 | * Implements JMeterGUIComponent.clearGui 135 | */ 136 | @Override 137 | public void clearGui() { 138 | super.clearGui(); 139 | 140 | serverPanel.clear(); 141 | classname.setText(""); //$NON-NLS-1$ 142 | requestData.setInitialText(""); //$NON-NLS-1$ 143 | reUseConnection.setSelected(true); 144 | setNoDelay.setSelected(false); // TODO should this be indeterminate? 145 | closeConnection.setSelected(TCPSampler.CLOSE_CONNECTION_DEFAULT); // TODO should this be indeterminate? 146 | soLinger.setText(""); //$NON-NLS-1$ 147 | eolByte.setText(""); //$NON-NLS-1$ 148 | responseLenth.setText(""); 149 | } 150 | 151 | 152 | private JPanel createNoDelayPanel() { 153 | JLabel label = new JLabel(JMeterUtils.getResString("tcp_nodelay")); // $NON-NLS-1$ 154 | 155 | setNoDelay = new TristateCheckBox(); 156 | label.setLabelFor(setNoDelay); 157 | 158 | JPanel nodelayPanel = new JPanel(new FlowLayout()); 159 | nodelayPanel.add(label); 160 | nodelayPanel.add(setNoDelay); 161 | return nodelayPanel; 162 | } 163 | 164 | private JPanel createClosePortPanel() { 165 | JLabel label = new JLabel(JMeterUtils.getResString("reuseconnection")); //$NON-NLS-1$ 166 | 167 | reUseConnection = new JCheckBox("", true); 168 | reUseConnection.addItemListener(e -> { 169 | if (e.getStateChange() == ItemEvent.SELECTED) { 170 | closeConnection.setEnabled(true); 171 | } else { 172 | closeConnection.setEnabled(false); 173 | } 174 | }); 175 | label.setLabelFor(reUseConnection); 176 | 177 | JPanel closePortPanel = new JPanel(new FlowLayout()); 178 | closePortPanel.add(label); 179 | closePortPanel.add(reUseConnection); 180 | return closePortPanel; 181 | } 182 | 183 | private JPanel createCloseConnectionPanel() { 184 | JLabel label = new JLabel(JMeterUtils.getResString("closeconnection")); // $NON-NLS-1$ 185 | 186 | closeConnection = new TristateCheckBox("", TCPSampler.CLOSE_CONNECTION_DEFAULT); 187 | label.setLabelFor(closeConnection); 188 | 189 | JPanel closeConnectionPanel = new JPanel(new FlowLayout()); 190 | closeConnectionPanel.add(label); 191 | closeConnectionPanel.add(closeConnection); 192 | return closeConnectionPanel; 193 | } 194 | 195 | private JPanel createSoLingerOption() { 196 | JLabel label = new JLabel(JMeterUtils.getResString("solinger")); //$NON-NLS-1$ 197 | 198 | soLinger = new JTextField(5); // 5 columns size 199 | soLinger.setMaximumSize(new Dimension(soLinger.getPreferredSize())); 200 | label.setLabelFor(soLinger); 201 | 202 | JPanel soLingerPanel = new JPanel(new FlowLayout()); 203 | soLingerPanel.add(label); 204 | soLingerPanel.add(soLinger); 205 | return soLingerPanel; 206 | } 207 | 208 | private JPanel createEolBytePanel() { 209 | JLabel label = new JLabel(JMeterUtils.getResString("eolbyte")); //$NON-NLS-1$ 210 | 211 | eolByte = new JTextField(3); // 3 columns size 212 | eolByte.setMaximumSize(new Dimension(eolByte.getPreferredSize())); 213 | label.setLabelFor(eolByte); 214 | 215 | JPanel eolBytePanel = new JPanel(new FlowLayout()); 216 | eolBytePanel.add(label); 217 | eolBytePanel.add(eolByte); 218 | return eolBytePanel; 219 | } 220 | 221 | private JPanel createLengthPanel() { 222 | JLabel label = new JLabel(JMeterUtils.getResString("response_length")); //$NON-NLS-1$ 223 | 224 | responseLenth = new JTextField(3); // 3 columns size 225 | responseLenth.setMaximumSize(new Dimension(responseLenth.getPreferredSize())); 226 | label.setLabelFor(responseLenth); 227 | 228 | JPanel eolBytePanel = new JPanel(new FlowLayout()); 229 | eolBytePanel.add(label); 230 | eolBytePanel.add(responseLenth); 231 | return eolBytePanel; 232 | } 233 | 234 | private JPanel createRequestPanel() { 235 | JLabel reqLabel = new JLabel(JMeterUtils.getResString("tcp_request_data")); // $NON-NLS-1$ 236 | requestData = JSyntaxTextArea.getInstance(15, 80); 237 | requestData.setLanguage("text"); //$NON-NLS-1$ 238 | reqLabel.setLabelFor(requestData); 239 | 240 | JPanel reqDataPanel = new JPanel(new BorderLayout(5, 0)); 241 | reqDataPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder())); 242 | 243 | reqDataPanel.add(reqLabel, BorderLayout.WEST); 244 | reqDataPanel.add(JTextScrollPane.getInstance(requestData), BorderLayout.CENTER); 245 | return reqDataPanel; 246 | } 247 | 248 | private void init() { // WARNING: called from ctor so must not be overridden (i.e. must be private or final) 249 | setLayout(new BorderLayout(0, 5)); 250 | 251 | serverPanel = new ServerPanel(); 252 | 253 | if (displayName) { 254 | setBorder(makeBorder()); 255 | add(makeTitlePanel(), BorderLayout.NORTH); 256 | } 257 | 258 | VerticalPanel mainPanel = new VerticalPanel(); 259 | classname = new JLabeledTextField(JMeterUtils.getResString("tcp_classname")); // $NON-NLS-1$ 260 | mainPanel.add(classname); 261 | mainPanel.add(serverPanel); 262 | 263 | HorizontalPanel optionsPanel = new HorizontalPanel(); 264 | optionsPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder())); 265 | optionsPanel.add(createClosePortPanel()); 266 | optionsPanel.add(createCloseConnectionPanel()); 267 | optionsPanel.add(createNoDelayPanel()); 268 | optionsPanel.add(createSoLingerOption()); 269 | optionsPanel.add(createEolBytePanel()); 270 | optionsPanel.add(createLengthPanel()); 271 | mainPanel.add(optionsPanel); 272 | mainPanel.add(createRequestPanel()); 273 | 274 | add(mainPanel, BorderLayout.CENTER); 275 | } 276 | } 277 | -------------------------------------------------------------------------------- /tcp/src/protocol/tcp/org/apache/jmeter/protocol/tcp/control/gui/TCPSamplerGui.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | */ 18 | 19 | package org.apache.jmeter.protocol.tcp.control.gui; 20 | 21 | import java.awt.BorderLayout; 22 | 23 | import javax.swing.BorderFactory; 24 | 25 | import org.apache.jmeter.config.gui.LoginConfigGui; 26 | import org.apache.jmeter.gui.util.VerticalPanel; 27 | import org.apache.jmeter.protocol.tcp.config.gui.TCPConfigGui; 28 | import org.apache.jmeter.protocol.tcp.sampler.TCPSampler; 29 | import org.apache.jmeter.samplers.gui.AbstractSamplerGui; 30 | import org.apache.jmeter.testelement.TestElement; 31 | import org.apache.jmeter.util.JMeterUtils; 32 | 33 | public class TCPSamplerGui extends AbstractSamplerGui { 34 | 35 | private static final long serialVersionUID = 240L; 36 | 37 | private LoginConfigGui loginPanel; 38 | private TCPConfigGui tcpDefaultPanel; 39 | 40 | public TCPSamplerGui() { 41 | init(); 42 | } 43 | 44 | @Override 45 | public void configure(TestElement element) { 46 | super.configure(element); 47 | loginPanel.configure(element); 48 | tcpDefaultPanel.configure(element); 49 | } 50 | 51 | @Override 52 | public TestElement createTestElement() { 53 | TCPSampler sampler = new TCPSampler(); 54 | modifyTestElement(sampler); 55 | return sampler; 56 | } 57 | 58 | /** 59 | * Modifies a given TestElement to mirror the data in the gui components. 60 | * 61 | * @see org.apache.jmeter.gui.JMeterGUIComponent#modifyTestElement(TestElement) 62 | */ 63 | @Override 64 | public void modifyTestElement(TestElement sampler) { 65 | sampler.clear(); 66 | sampler.addTestElement(tcpDefaultPanel.createTestElement()); 67 | sampler.addTestElement(loginPanel.createTestElement()); 68 | super.configureTestElement(sampler); 69 | } 70 | 71 | /** 72 | * Implements JMeterGUIComponent.clearGui 73 | */ 74 | @Override 75 | public void clearGui() { 76 | super.clearGui(); 77 | 78 | tcpDefaultPanel.clearGui(); 79 | loginPanel.clearGui(); 80 | } 81 | 82 | @Override 83 | public String getLabelResource() { 84 | return "tcp_sample_title"; // $NON-NLS-1$ 85 | } 86 | 87 | private void init() { // WARNING: called from ctor so must not be overridden (i.e. must be private or final) 88 | setLayout(new BorderLayout(0, 5)); 89 | setBorder(makeBorder()); 90 | 91 | add(makeTitlePanel(), BorderLayout.NORTH); 92 | 93 | VerticalPanel mainPanel = new VerticalPanel(); 94 | 95 | tcpDefaultPanel = new TCPConfigGui(false); 96 | mainPanel.add(tcpDefaultPanel); 97 | 98 | loginPanel = new LoginConfigGui(false); 99 | loginPanel.setBorder(BorderFactory.createTitledBorder(JMeterUtils.getResString("login_config"))); // $NON-NLS-1$ 100 | mainPanel.add(loginPanel); 101 | 102 | add(mainPanel, BorderLayout.CENTER); 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /tcp/src/protocol/tcp/org/apache/jmeter/protocol/tcp/sampler/AbstractTCPClient.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | */ 18 | 19 | package org.apache.jmeter.protocol.tcp.sampler; 20 | 21 | import java.io.InputStream; 22 | 23 | import org.apache.jmeter.samplers.SampleResult; 24 | 25 | /** 26 | * Basic implementation of TCPClient interface. 27 | */ 28 | public abstract class AbstractTCPClient implements TCPClient { 29 | private String charset; 30 | protected byte eolByte; 31 | protected boolean useEolByte = false; 32 | protected int length = -1; 33 | /** 34 | * {@inheritDoc} 35 | */ 36 | @Override 37 | public byte getEolByte() { 38 | return eolByte; 39 | } 40 | 41 | /** 42 | * {@inheritDoc} 43 | */ 44 | @Override 45 | public void setEolByte(int eolInt) { 46 | if (eolInt >= Byte.MIN_VALUE && eolInt <= Byte.MAX_VALUE) { 47 | this.eolByte = (byte) eolInt; 48 | useEolByte = true; 49 | } else { 50 | useEolByte = false; 51 | } 52 | } 53 | 54 | /** 55 | * {@inheritDoc} 56 | */ 57 | @Override 58 | public void setupTest() { 59 | } 60 | 61 | /** 62 | * {@inheritDoc} 63 | */ 64 | @Override 65 | public void teardownTest() { 66 | } 67 | 68 | /** 69 | * @return the charset 70 | */ 71 | @Override 72 | public String getCharset() { 73 | return charset; 74 | } 75 | 76 | /** 77 | * @param charset the charset to set 78 | */ 79 | public void setCharset(String charset) { 80 | this.charset = charset; 81 | } 82 | 83 | /** 84 | * Default implementation calls {@link TCPClient#read(InputStream)} for backward compatibility 85 | * @see org.apache.jmeter.protocol.tcp.sampler.TCPClient#read(java.io.InputStream, org.apache.jmeter.samplers.SampleResult) 86 | */ 87 | @Override 88 | public String read(InputStream is, SampleResult sampleResult) throws ReadException { 89 | return read(is); 90 | } 91 | 92 | @Override 93 | public int getLength() { 94 | if(useEolByte) { 95 | return -1; 96 | } 97 | return length; 98 | } 99 | 100 | @Override 101 | public void setLength(int length) { 102 | this.length = length; 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /tcp/src/protocol/tcp/org/apache/jmeter/protocol/tcp/sampler/BinaryTCPClientImpl.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | */ 18 | 19 | /* 20 | * TCP Sampler Client implementation which reads and writes binary data. 21 | * 22 | * Input/Output strings are passed as hex-encoded binary strings. 23 | * 24 | */ 25 | package org.apache.jmeter.protocol.tcp.sampler; 26 | 27 | import java.io.ByteArrayOutputStream; 28 | import java.io.IOException; 29 | import java.io.InputStream; 30 | import java.io.OutputStream; 31 | 32 | import org.apache.commons.io.IOUtils; 33 | import org.apache.jmeter.samplers.SampleResult; 34 | import org.apache.jmeter.util.JMeterUtils; 35 | import org.apache.jorphan.util.JOrphanUtils; 36 | import org.slf4j.Logger; 37 | import org.slf4j.LoggerFactory; 38 | 39 | /** 40 | * TCPClient implementation. 41 | * Reads data until the defined EOM byte is reached. 42 | * If there is no EOM byte defined, then reads until 43 | * the end of the stream is reached. 44 | * The EOM byte is defined by the property "tcp.BinaryTCPClient.eomByte". 45 | * 46 | * Input data is assumed to be in hex, and is converted to binary 47 | */ 48 | public class BinaryTCPClientImpl extends AbstractTCPClient { 49 | private static final Logger log = LoggerFactory.getLogger(BinaryTCPClientImpl.class); 50 | 51 | private static final int EOM_INT = JMeterUtils.getPropDefault("tcp.BinaryTCPClient.eomByte", 1000); // $NON_NLS-1$ 52 | 53 | public BinaryTCPClientImpl() { 54 | super(); 55 | setEolByte(EOM_INT); 56 | if (useEolByte) { 57 | log.info("Using eomByte={}", eolByte); 58 | } 59 | } 60 | 61 | /** 62 | * Convert hex string to binary byte array. 63 | * 64 | * @param hexEncodedBinary - hex-encoded binary string 65 | * @return Byte array containing binary representation of input hex-encoded string 66 | * @throws IllegalArgumentException if string is not an even number of hex digits 67 | */ 68 | public static byte[] hexStringToByteArray(String hexEncodedBinary) { 69 | if (hexEncodedBinary.length() % 2 == 0) { 70 | char[] sc = hexEncodedBinary.toCharArray(); 71 | byte[] ba = new byte[sc.length / 2]; 72 | 73 | for (int i = 0; i < ba.length; i++) { 74 | int nibble0 = Character.digit(sc[i * 2], 16); 75 | int nibble1 = Character.digit(sc[i * 2 + 1], 16); 76 | if (nibble0 == -1 || nibble1 == -1){ 77 | throw new IllegalArgumentException( 78 | "Hex-encoded binary string contains an invalid hex digit in '"+sc[i * 2]+sc[i * 2 + 1]+"'"); 79 | } 80 | ba[i] = (byte) ((nibble0 << 4) | nibble1); 81 | } 82 | 83 | return ba; 84 | } else { 85 | throw new IllegalArgumentException( 86 | "Hex-encoded binary string contains an uneven no. of digits"); 87 | } 88 | } 89 | 90 | /** 91 | * Input (hex) string is converted to binary and written to the output stream. 92 | * @param os output stream 93 | * @param hexEncodedBinary hex-encoded binary 94 | */ 95 | @Override 96 | public void write(OutputStream os, String hexEncodedBinary) throws IOException{ 97 | os.write(hexStringToByteArray(hexEncodedBinary)); 98 | os.flush(); 99 | if(log.isDebugEnabled()) { 100 | log.debug("Wrote: " + hexEncodedBinary); 101 | } 102 | } 103 | 104 | /** 105 | * {@inheritDoc} 106 | */ 107 | @Override 108 | public void write(OutputStream os, InputStream is) { 109 | throw new UnsupportedOperationException( 110 | "Method not supported for Length-Prefixed data."); 111 | } 112 | 113 | @Deprecated 114 | public String read(InputStream is) throws ReadException { 115 | log.warn("Deprecated method, use read(is, sampleResult) instead"); 116 | return read(is, new SampleResult()); 117 | } 118 | 119 | /** 120 | * Reads data until the defined EOM byte is reached. 121 | * If there is no EOM byte defined, then reads until 122 | * the end of the stream is reached. 123 | * Response data is converted to hex-encoded binary 124 | * @return hex-encoded binary string 125 | * @throws ReadException when reading fails 126 | */ 127 | @Override 128 | public String read(InputStream is, SampleResult sampleResult) throws ReadException { 129 | ByteArrayOutputStream w = new ByteArrayOutputStream(); 130 | try { 131 | byte[] buffer = new byte[4096]; 132 | int x = 0; 133 | boolean first = true; 134 | if(getLength() == -1) { 135 | while ((x = is.read(buffer)) > -1) { 136 | if (first) { 137 | sampleResult.latencyEnd(); 138 | first = false; 139 | } 140 | w.write(buffer, 0, x); 141 | if (useEolByte && (buffer[x - 1] == eolByte)) { 142 | break; 143 | } 144 | } 145 | } else { 146 | buffer = new byte[length]; 147 | if ((x = is.read(buffer, 0, length)) > -1) { 148 | sampleResult.latencyEnd(); 149 | w.write(buffer, 0, x); 150 | } 151 | } 152 | 153 | IOUtils.closeQuietly(w); // For completeness 154 | final String hexString = JOrphanUtils.baToHexString(w.toByteArray()); 155 | if(log.isDebugEnabled()) { 156 | log.debug("Read: " + w.size() + "\n" + hexString); 157 | } 158 | return hexString; 159 | } catch (IOException e) { 160 | throw new ReadException("", e, JOrphanUtils.baToHexString(w.toByteArray())); 161 | } 162 | } 163 | 164 | } 165 | -------------------------------------------------------------------------------- /tcp/src/protocol/tcp/org/apache/jmeter/protocol/tcp/sampler/LengthPrefixedBinaryTCPClientImpl.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | */ 18 | 19 | /* 20 | * TCP Sampler Client implementation which reads and writes length-prefixed binary data. 21 | * 22 | * Input/Output strings are passed as hex-encoded binary strings. 23 | * 24 | * 2-Byte or 4-Byte length prefixes are supported. 25 | * 26 | * Length prefix is binary of length specified by property "tcp.length.prefix.length". 27 | * 28 | */ 29 | package org.apache.jmeter.protocol.tcp.sampler; 30 | 31 | import java.io.IOException; 32 | import java.io.InputStream; 33 | import java.io.OutputStream; 34 | 35 | import org.apache.jmeter.samplers.SampleResult; 36 | import org.apache.jmeter.util.JMeterUtils; 37 | import org.apache.jorphan.util.JOrphanUtils; 38 | import org.slf4j.Logger; 39 | import org.slf4j.LoggerFactory; 40 | 41 | /** 42 | * Implements binary length-prefixed binary data. 43 | * This is used in ISO8583 for example. 44 | */ 45 | public class LengthPrefixedBinaryTCPClientImpl extends TCPClientDecorator { 46 | private static final Logger log = LoggerFactory.getLogger(LengthPrefixedBinaryTCPClientImpl.class); 47 | 48 | private final int lengthPrefixLen = JMeterUtils.getPropDefault("tcp.binarylength.prefix.length", 2); // $NON-NLS-1$ 49 | 50 | public LengthPrefixedBinaryTCPClientImpl() { 51 | super(new BinaryTCPClientImpl()); 52 | tcpClient.setEolByte(Byte.MAX_VALUE+1); 53 | } 54 | 55 | 56 | /** 57 | * {@inheritDoc} 58 | */ 59 | @Override 60 | public void write(OutputStream os, String s) throws IOException{ 61 | os.write(intToByteArray(s.length()/2,lengthPrefixLen)); 62 | if(log.isDebugEnabled()) { 63 | log.debug("Wrote: " + s.length()/2 + " bytes"); 64 | } 65 | this.tcpClient.write(os, s); 66 | } 67 | 68 | /** 69 | * {@inheritDoc} 70 | */ 71 | @Override 72 | public void write(OutputStream os, InputStream is) throws IOException { 73 | this.tcpClient.write(os, is); 74 | } 75 | 76 | @Deprecated 77 | public String read(InputStream is) throws ReadException { 78 | log.warn("Deprecated method, use read(is, sampleResult) instead"); 79 | return read(is, new SampleResult()); 80 | } 81 | 82 | /** 83 | * {@inheritDoc} 84 | */ 85 | @Override 86 | public String read(InputStream is, SampleResult sampleResult) throws ReadException{ 87 | byte[] msg = new byte[0]; 88 | int msgLen = 0; 89 | byte[] lengthBuffer = new byte[lengthPrefixLen]; 90 | try { 91 | if (is.read(lengthBuffer, 0, lengthPrefixLen) == lengthPrefixLen) { 92 | sampleResult.latencyEnd(); 93 | msgLen = byteArrayToInt(lengthBuffer); 94 | msg = new byte[msgLen]; 95 | int bytes = JOrphanUtils.read(is, msg, 0, msgLen); 96 | if (bytes < msgLen) { 97 | log.warn("Incomplete message read, expected: {} got: {}", msgLen, bytes); 98 | } 99 | } 100 | 101 | String buffer = JOrphanUtils.baToHexString(msg); 102 | if(log.isDebugEnabled()) { 103 | log.debug("Read: " + msgLen + "\n" + buffer); 104 | } 105 | return buffer; 106 | } 107 | catch(IOException e) { 108 | throw new ReadException("", e, JOrphanUtils.baToHexString(msg)); 109 | } 110 | } 111 | 112 | /** 113 | * Not useful, as the byte is never used. 114 | *

115 | * {@inheritDoc} 116 | */ 117 | @Override 118 | public byte getEolByte() { 119 | return tcpClient.getEolByte(); 120 | } 121 | 122 | /** 123 | * {@inheritDoc} 124 | */ 125 | @Override 126 | public void setEolByte(int eolInt) { 127 | throw new UnsupportedOperationException("Cannot set eomByte for prefixed messages"); 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /tcp/src/protocol/tcp/org/apache/jmeter/protocol/tcp/sampler/ReadException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | */ 18 | package org.apache.jmeter.protocol.tcp.sampler; 19 | 20 | /** 21 | * Exception that contains partial response (Text read until exception occurred) 22 | */ 23 | public class ReadException extends Exception { 24 | 25 | private static final long serialVersionUID = -2770054697780959330L; 26 | private final String partialResponse; 27 | 28 | /** 29 | * @deprecated For use by test code only (serialisation tests) 30 | */ 31 | @Deprecated 32 | public ReadException() { 33 | this(null, null, null); 34 | } 35 | 36 | /** 37 | * Constructor 38 | * @param message Message 39 | * @param cause Source cause 40 | * @param partialResponse Text read until error occurred 41 | */ 42 | public ReadException(String message, Throwable cause, String partialResponse) { 43 | super(message, cause); 44 | this.partialResponse = partialResponse; 45 | } 46 | 47 | /** 48 | * @return the partialResponse Text read until error occurred 49 | */ 50 | public String getPartialResponse() { 51 | return partialResponse; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /tcp/src/protocol/tcp/org/apache/jmeter/protocol/tcp/sampler/TCPClient.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | */ 18 | 19 | /* 20 | * Created on 24-Sep-2003 21 | * 22 | * Interface for generic TCP protocol handler 23 | * 24 | */ 25 | package org.apache.jmeter.protocol.tcp.sampler; 26 | 27 | import java.io.IOException; 28 | import java.io.InputStream; 29 | import java.io.OutputStream; 30 | 31 | import org.apache.jmeter.samplers.SampleResult; 32 | 33 | /** 34 | * Interface required by TCPSampler for TCPClient implementations. 35 | */ 36 | public interface TCPClient { 37 | 38 | /** 39 | * Invoked when the thread starts. 40 | */ 41 | void setupTest(); 42 | 43 | /** 44 | * Invoked when the thread ends 45 | */ 46 | void teardownTest(); 47 | 48 | /** 49 | * 50 | * @param os - 51 | * OutputStream for socket 52 | * @param is - 53 | * InputStream to be written to Socket 54 | * @throws IOException when writing fails 55 | */ 56 | void write(OutputStream os, InputStream is) throws IOException; 57 | 58 | /** 59 | * 60 | * @param os - 61 | * OutputStream for socket 62 | * @param s - 63 | * String to write 64 | * @throws IOException when writing fails 65 | */ 66 | void write(OutputStream os, String s) throws IOException; 67 | 68 | /** 69 | * 70 | * @param is - 71 | * InputStream for socket 72 | * @return String read from socket 73 | * @throws ReadException exception that can contain partial response (Response until error occurred) 74 | * @deprecated since 3.3, implement {@link TCPClient#read(InputStream, SampleResult)} instead, will be removed in future version 75 | */ 76 | @Deprecated 77 | String read(InputStream is) throws ReadException; 78 | 79 | /** 80 | * 81 | * @param is - 82 | * InputStream for socket 83 | * @param sampleResult {@link SampleResult} 84 | * @return String read from socket 85 | * @throws ReadException exception that can contain partial response 86 | */ 87 | String read(InputStream is, SampleResult sampleResult) throws ReadException; 88 | 89 | /** 90 | * Get the end-of-line/end-of-message byte. 91 | * @return Returns the eolByte. 92 | */ 93 | byte getEolByte(); 94 | 95 | 96 | /** 97 | * Get the charset. 98 | * @return Returns the charset. 99 | */ 100 | String getCharset(); 101 | 102 | /** 103 | * Set the end-of-line/end-of-message byte. 104 | * If the value is out of range of a byte, then it is to be ignored. 105 | * 106 | * @param eolInt 107 | * The value to set 108 | */ 109 | void setEolByte(int eolInt); 110 | 111 | /** 112 | * Get the response length setting 113 | * 114 | * @return 115 | */ 116 | int getLength(); 117 | 118 | 119 | /** 120 | * Set the length of returned response. 121 | * 122 | * @param length 123 | */ 124 | void setLength(int length); 125 | } 126 | -------------------------------------------------------------------------------- /tcp/src/protocol/tcp/org/apache/jmeter/protocol/tcp/sampler/TCPClientDecorator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | */ 18 | 19 | /* 20 | * TCP Sampler Client decorator to permit wrapping base client implementations with length prefixes. 21 | * For example, character data or binary data with character length or binary length 22 | * 23 | */ 24 | package org.apache.jmeter.protocol.tcp.sampler; 25 | 26 | public abstract class TCPClientDecorator extends AbstractTCPClient { 27 | 28 | protected final TCPClient tcpClient; // the data implementation 29 | 30 | public TCPClientDecorator(TCPClient tcpClient) { 31 | this.tcpClient = tcpClient; 32 | } 33 | 34 | /** 35 | * Convert int to byte array. 36 | * 37 | * @param value 38 | * - int to be converted 39 | * @param len 40 | * - length of required byte array 41 | * @return Byte array representation of input value 42 | * @throws IllegalArgumentException if not length 2 or 4 or outside range of a short int. 43 | */ 44 | public static byte[] intToByteArray(int value, int len) { 45 | if (len == 2 || len == 4) { 46 | if (len == 2 && (value < Short.MIN_VALUE || value > Short.MAX_VALUE)) { 47 | throw new IllegalArgumentException("Value outside range for signed short int."); 48 | } else { 49 | byte[] b = new byte[len]; 50 | for (int i = 0; i < len; i++) { 51 | int offset = (b.length - 1 - i) * 8; 52 | b[i] = (byte) ((value >>> offset) & 0xFF); 53 | } 54 | return b; 55 | } 56 | } else { 57 | throw new IllegalArgumentException( 58 | "Length must be specified as either 2 or 4."); 59 | } 60 | } 61 | 62 | /** 63 | * Convert byte array to int. 64 | * 65 | * @param b 66 | * - Byte array to be converted 67 | * @return Integer value of input byte array 68 | * @throws IllegalArgumentException if ba is null or not length 2 or 4 69 | */ 70 | public static int byteArrayToInt(byte[] b) { 71 | if (b != null && (b.length == 2 || b.length == 4)) { 72 | // Preserve sign on first byte 73 | int value = b[0] << ((b.length - 1) * 8); 74 | 75 | for (int i = 1; i < b.length; i++) { 76 | int offset = (b.length - 1 - i) * 8; 77 | value += (b[i] & 0xFF) << offset; 78 | } 79 | return value; 80 | } else { 81 | throw new IllegalArgumentException( 82 | "Byte array is null or invalid length."); 83 | } 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /tcp/src/protocol/tcp/org/apache/jmeter/protocol/tcp/sampler/TCPClientImpl.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | */ 18 | 19 | /* 20 | * Basic TCP Sampler Client class 21 | * 22 | * Can be used to test the TCP Sampler against an HTTP server 23 | * 24 | * The protocol handler class name is defined by the property tcp.handler 25 | * 26 | */ 27 | package org.apache.jmeter.protocol.tcp.sampler; 28 | 29 | import java.io.ByteArrayOutputStream; 30 | import java.io.IOException; 31 | import java.io.InputStream; 32 | import java.io.OutputStream; 33 | import java.nio.charset.Charset; 34 | 35 | import org.apache.commons.lang3.StringUtils; 36 | import org.apache.jmeter.samplers.SampleResult; 37 | import org.apache.jmeter.util.JMeterUtils; 38 | import org.slf4j.Logger; 39 | import org.slf4j.LoggerFactory; 40 | 41 | /** 42 | * Sample TCPClient implementation. 43 | * Reads data until the defined EOL byte is reached. 44 | * If there is no EOL byte defined, then reads until 45 | * the end of the stream is reached. 46 | * The EOL byte is defined by the property "tcp.eolByte". 47 | */ 48 | public class TCPClientImpl extends AbstractTCPClient { 49 | private static final Logger log = LoggerFactory.getLogger(TCPClientImpl.class); 50 | 51 | private static final int EOL_INT = JMeterUtils.getPropDefault("tcp.eolByte", 1000); // $NON-NLS-1$ 52 | private static final String CHARSET = JMeterUtils.getPropDefault("tcp.charset", Charset.defaultCharset().name()); // $NON-NLS-1$ 53 | // default is not in range of a byte 54 | 55 | public TCPClientImpl() { 56 | super(); 57 | setEolByte(EOL_INT); 58 | if (useEolByte) { 59 | log.info("Using eolByte={}", eolByte); 60 | } 61 | setCharset(CHARSET); 62 | String configuredCharset = JMeterUtils.getProperty("tcp.charset"); 63 | if(StringUtils.isEmpty(configuredCharset)) { 64 | log.info("Using platform default charset:{}",CHARSET); 65 | } else { 66 | log.info("Using charset:{}", configuredCharset); 67 | } 68 | } 69 | 70 | /** 71 | * {@inheritDoc} 72 | */ 73 | @Override 74 | public void write(OutputStream os, String s) throws IOException{ 75 | if(log.isDebugEnabled()) { 76 | log.debug("WriteS: {}", showEOL(s)); 77 | } 78 | os.write(s.getBytes(CHARSET)); 79 | os.flush(); 80 | } 81 | 82 | /** 83 | * {@inheritDoc} 84 | */ 85 | @Override 86 | public void write(OutputStream os, InputStream is) throws IOException{ 87 | byte[] buff = new byte[512]; 88 | while(is.read(buff) > 0){ 89 | if(log.isDebugEnabled()) { 90 | log.debug("WriteIS: {}", showEOL(new String(buff, CHARSET))); 91 | } 92 | os.write(buff); 93 | os.flush(); 94 | } 95 | } 96 | 97 | @Deprecated 98 | public String read(InputStream is) throws ReadException { 99 | return read(is, new SampleResult()); 100 | } 101 | 102 | /** 103 | * Reads data until the defined EOL byte is reached. 104 | * If there is no EOL byte defined, then reads until 105 | * the end of the stream is reached. 106 | */ 107 | @Override 108 | public String read(InputStream is, SampleResult sampleResult) throws ReadException{ 109 | ByteArrayOutputStream w = new ByteArrayOutputStream(); 110 | try { 111 | byte[] buffer = new byte[4096]; 112 | int x; 113 | boolean first = true; 114 | if(getLength() == -1) { 115 | while ((x = is.read(buffer)) > -1) { 116 | if (first) { 117 | sampleResult.latencyEnd(); 118 | first = false; 119 | } 120 | w.write(buffer, 0, x); 121 | if (useEolByte && (buffer[x - 1] == eolByte)) { 122 | break; 123 | } 124 | } 125 | } else { 126 | buffer = new byte[length]; 127 | if ((x = is.read(buffer, 0, length)) > -1) { 128 | sampleResult.latencyEnd(); 129 | w.write(buffer, 0, x); 130 | } 131 | } 132 | 133 | // do we need to close byte array (or flush it?) 134 | if(log.isDebugEnabled()) { 135 | log.debug("Read: {}\n{}", w.size(), w.toString()); 136 | } 137 | return w.toString(CHARSET); 138 | } catch (IOException e) { 139 | throw new ReadException("Error reading from server, bytes read: " + w.size(), e, w.toString()); 140 | } 141 | } 142 | 143 | private String showEOL(final String input) { 144 | StringBuilder sb = new StringBuilder(input.length()*2); 145 | for(int i=0; i < input.length(); i++) { 146 | char ch = input.charAt(i); 147 | if (ch < ' ') { 148 | sb.append('['); 149 | sb.append((int)ch); 150 | sb.append(']'); 151 | } else { 152 | sb.append(ch); 153 | } 154 | } 155 | return sb.toString(); 156 | } 157 | } 158 | -------------------------------------------------------------------------------- /tcp/src/protocol/tcp/org/apache/jmeter/protocol/tcp/sampler/TCPSampler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | */ 18 | 19 | package org.apache.jmeter.protocol.tcp.sampler; 20 | 21 | import java.io.File; 22 | import java.io.FileInputStream; 23 | import java.io.FileNotFoundException; 24 | import java.io.IOException; 25 | import java.io.InputStream; 26 | import java.io.OutputStream; 27 | import java.net.InetSocketAddress; 28 | import java.net.Socket; 29 | import java.net.SocketAddress; 30 | import java.net.SocketException; 31 | import java.net.UnknownHostException; 32 | import java.util.Arrays; 33 | import java.util.HashMap; 34 | import java.util.HashSet; 35 | import java.util.Map; 36 | import java.util.Optional; 37 | import java.util.Properties; 38 | import java.util.Set; 39 | 40 | import org.apache.commons.lang3.StringUtils; 41 | import org.apache.jmeter.config.ConfigTestElement; 42 | import org.apache.jmeter.samplers.AbstractSampler; 43 | import org.apache.jmeter.samplers.Entry; 44 | import org.apache.jmeter.samplers.Interruptible; 45 | import org.apache.jmeter.samplers.SampleResult; 46 | import org.apache.jmeter.testelement.TestElement; 47 | import org.apache.jmeter.testelement.ThreadListener; 48 | import org.apache.jmeter.util.JMeterUtils; 49 | import org.slf4j.Logger; 50 | import org.slf4j.LoggerFactory; 51 | 52 | /** 53 | * A sampler which understands Tcp requests. 54 | * 55 | */ 56 | public class TCPSampler extends AbstractSampler implements ThreadListener, Interruptible { 57 | private static final long serialVersionUID = 280L; 58 | 59 | private static final Logger log = LoggerFactory.getLogger(TCPSampler.class); 60 | 61 | private static final Set APPLIABLE_CONFIG_CLASSES = new HashSet<>( 62 | Arrays.asList( 63 | "org.apache.jmeter.config.gui.LoginConfigGui", 64 | "org.apache.jmeter.protocol.tcp.config.gui.TCPConfigGui", 65 | "org.apache.jmeter.config.gui.SimpleConfigGui" 66 | )); 67 | 68 | public static final String SERVER = "TCPSampler.server"; //$NON-NLS-1$ 69 | 70 | public static final String PORT = "TCPSampler.port"; //$NON-NLS-1$ 71 | 72 | public static final String FILENAME = "TCPSampler.filename"; //$NON-NLS-1$ 73 | 74 | public static final String CLASSNAME = "TCPSampler.classname";//$NON-NLS-1$ 75 | 76 | public static final String NODELAY = "TCPSampler.nodelay"; //$NON-NLS-1$ 77 | 78 | public static final String TIMEOUT = "TCPSampler.timeout"; //$NON-NLS-1$ 79 | 80 | public static final String TIMEOUT_CONNECT = "TCPSampler.ctimeout"; //$NON-NLS-1$ 81 | 82 | public static final String REQUEST = "TCPSampler.request"; //$NON-NLS-1$ 83 | 84 | public static final String RE_USE_CONNECTION = "TCPSampler.reUseConnection"; //$NON-NLS-1$ 85 | public static final boolean RE_USE_CONNECTION_DEFAULT = true; 86 | 87 | public static final String CLOSE_CONNECTION = "TCPSampler.closeConnection"; //$NON-NLS-1$ 88 | public static final boolean CLOSE_CONNECTION_DEFAULT = false; 89 | 90 | public static final String SO_LINGER = "TCPSampler.soLinger"; //$NON-NLS-1$ 91 | 92 | public static final String EOL_BYTE = "TCPSampler.EolByte"; //$NON-NLS-1$ 93 | 94 | public static final String LENGTH = "TCPSampler.length"; //$NON-NLS-1$ 95 | 96 | private static final String TCPKEY = "TCP"; //$NON-NLS-1$ key for HashMap 97 | 98 | private static final String ERRKEY = "ERR"; //$NON-NLS-1$ key for HashMap 99 | 100 | // the response is scanned for these strings 101 | private static final String STATUS_PREFIX = JMeterUtils.getPropDefault("tcp.status.prefix", ""); //$NON-NLS-1$ 102 | 103 | private static final String STATUS_SUFFIX = JMeterUtils.getPropDefault("tcp.status.suffix", ""); //$NON-NLS-1$ 104 | 105 | private static final String STATUS_PROPERTIES = JMeterUtils.getPropDefault("tcp.status.properties", ""); //$NON-NLS-1$ 106 | 107 | private static final Properties STATUS_PROPS = new Properties(); 108 | 109 | private static final String PROTO_PREFIX = "org.apache.jmeter.protocol.tcp.sampler."; //$NON-NLS-1$ 110 | 111 | private static final boolean HAVE_STATUS_PROPS; 112 | 113 | static { 114 | boolean hsp = false; 115 | log.debug("Status prefix={}, suffix={}, properties={}", 116 | STATUS_PREFIX, STATUS_SUFFIX, STATUS_PROPERTIES); //$NON-NLS-1$ 117 | if (STATUS_PROPERTIES.length() > 0) { 118 | File f = new File(STATUS_PROPERTIES); 119 | try (FileInputStream fis = new FileInputStream(f)){ 120 | STATUS_PROPS.load(fis); 121 | log.debug("Successfully loaded properties"); //$NON-NLS-1$ 122 | hsp = true; 123 | } catch (FileNotFoundException e) { 124 | log.debug("Property file {} not found", STATUS_PROPERTIES); //$NON-NLS-1$ 125 | } catch (IOException e) { 126 | log.debug("Error reading property file {} error {}", STATUS_PROPERTIES, e.toString()); //$NON-NLS-1$ 127 | } 128 | } 129 | HAVE_STATUS_PROPS = hsp; 130 | } 131 | 132 | /** the cache of TCP Connections */ 133 | // KEY = TCPKEY or ERRKEY, Entry= Socket or String 134 | private static final ThreadLocal> tp = 135 | ThreadLocal.withInitial(HashMap::new); 136 | 137 | private transient TCPClient protocolHandler; 138 | 139 | private transient boolean firstSample; // Are we processing the first sample? 140 | 141 | private transient volatile Socket currentSocket; // used for handling interrupt 142 | 143 | public TCPSampler() { 144 | log.debug("Created {}", this); //$NON-NLS-1$ 145 | } 146 | 147 | private String getError() { 148 | Map cp = tp.get(); 149 | return (String) cp.get(ERRKEY); 150 | } 151 | 152 | private Socket getSocket(String socketKey) { 153 | Map cp = tp.get(); 154 | Socket con = null; 155 | if (isReUseConnection()) { 156 | con = (Socket) cp.get(socketKey); 157 | if (con != null) { 158 | log.debug("{} Reusing connection {}", this, con); //$NON-NLS-1$ 159 | } 160 | } 161 | if (con == null) { 162 | // Not in cache, so create new one and cache it 163 | try { 164 | closeSocket(socketKey); // Bug 44910 - close previous socket (if any) 165 | SocketAddress sockaddr = new InetSocketAddress(getServer(), getPort()); 166 | con = new Socket(); // NOSONAR socket is either cache in ThreadLocal for reuse and closed at end of thread or closed here 167 | if (getPropertyAsString(SO_LINGER,"").length() > 0){ 168 | con.setSoLinger(true, getSoLinger()); 169 | } 170 | con.connect(sockaddr, getConnectTimeout()); 171 | if(log.isDebugEnabled()) { 172 | log.debug("Created new connection {}", con); //$NON-NLS-1$ 173 | } 174 | cp.put(socketKey, con); 175 | } catch (UnknownHostException e) { 176 | log.warn("Unknown host for {}", getLabel(), e);//$NON-NLS-1$ 177 | cp.put(ERRKEY, e.toString()); 178 | return null; 179 | } catch (IOException e) { 180 | log.warn("Could not create socket for {}", getLabel(), e); //$NON-NLS-1$ 181 | cp.put(ERRKEY, e.toString()); 182 | return null; 183 | } 184 | } 185 | // (re-)Define connection params - Bug 50977 186 | try { 187 | con.setSoTimeout(getTimeout()); 188 | con.setTcpNoDelay(getNoDelay()); 189 | if(log.isDebugEnabled()) { 190 | log.debug("{} Timeout={}, NoDelay={}", this, getTimeout(), getNoDelay()); //$NON-NLS-1$ 191 | } 192 | } catch (SocketException se) { 193 | log.warn("Could not set timeout or nodelay for {}", getLabel(), se); //$NON-NLS-1$ 194 | cp.put(ERRKEY, se.toString()); 195 | } 196 | return con; 197 | } 198 | 199 | /** 200 | * @return String socket key in cache Map 201 | */ 202 | private String getSocketKey() { 203 | return TCPKEY+"#"+getServer()+"#"+getPort()+"#"+getUsername()+"#"+getPassword(); 204 | } 205 | 206 | public String getUsername() { 207 | return getPropertyAsString(ConfigTestElement.USERNAME); 208 | } 209 | 210 | public String getPassword() { 211 | return getPropertyAsString(ConfigTestElement.PASSWORD); 212 | } 213 | 214 | public void setServer(String newServer) { 215 | this.setProperty(SERVER, newServer); 216 | } 217 | 218 | public String getServer() { 219 | return getPropertyAsString(SERVER); 220 | } 221 | 222 | public boolean isReUseConnection() { 223 | return getPropertyAsBoolean(RE_USE_CONNECTION, RE_USE_CONNECTION_DEFAULT); 224 | } 225 | 226 | public void setCloseConnection(String close) { 227 | this.setProperty(CLOSE_CONNECTION, close, ""); 228 | } 229 | 230 | public boolean isCloseConnection() { 231 | return getPropertyAsBoolean(CLOSE_CONNECTION, CLOSE_CONNECTION_DEFAULT); 232 | } 233 | 234 | public void setSoLinger(String soLinger) { 235 | this.setProperty(SO_LINGER, soLinger, ""); 236 | } 237 | 238 | public int getSoLinger() { 239 | return getPropertyAsInt(SO_LINGER); 240 | } 241 | 242 | public void setEolByte(String eol) { 243 | this.setProperty(EOL_BYTE, eol, ""); 244 | } 245 | 246 | public int getEolByte() { 247 | return getPropertyAsInt(EOL_BYTE); 248 | } 249 | 250 | 251 | public void setPort(String newFilename) { 252 | this.setProperty(PORT, newFilename); 253 | } 254 | 255 | public int getPort() { 256 | return getPropertyAsInt(PORT); 257 | } 258 | 259 | public void setFilename(String newFilename) { 260 | this.setProperty(FILENAME, newFilename); 261 | } 262 | 263 | public String getFilename() { 264 | return getPropertyAsString(FILENAME); 265 | } 266 | 267 | public void setRequestData(String newRequestData) { 268 | this.setProperty(REQUEST, newRequestData); 269 | } 270 | 271 | public String getRequestData() { 272 | return getPropertyAsString(REQUEST); 273 | } 274 | 275 | public void setTimeout(String newTimeout) { 276 | this.setProperty(TIMEOUT, newTimeout); 277 | } 278 | 279 | public int getTimeout() { 280 | return getPropertyAsInt(TIMEOUT); 281 | } 282 | 283 | public void setConnectTimeout(String newTimeout) { 284 | this.setProperty(TIMEOUT_CONNECT, newTimeout, ""); 285 | } 286 | 287 | public int getConnectTimeout() { 288 | return getPropertyAsInt(TIMEOUT_CONNECT, 0); 289 | } 290 | 291 | public boolean getNoDelay() { 292 | return getPropertyAsBoolean(NODELAY); 293 | } 294 | 295 | public void setClassname(String classname) { 296 | this.setProperty(CLASSNAME, classname, ""); //$NON-NLS-1$ 297 | } 298 | 299 | public String getClassname() { 300 | String clazz = getPropertyAsString(CLASSNAME,""); 301 | if (clazz==null || clazz.length()==0){ 302 | clazz = JMeterUtils.getPropDefault("tcp.handler", "TCPClientImpl"); //$NON-NLS-1$ $NON-NLS-2$ 303 | } 304 | return clazz; 305 | } 306 | 307 | /** 308 | * Returns a formatted string label describing this sampler Example output: 309 | * Tcp://Tcp.nowhere.com/pub/README.txt 310 | * 311 | * @return a formatted string label describing this sampler 312 | */ 313 | public String getLabel() { 314 | return "tcp://" + this.getServer() + ":" + this.getPort();//$NON-NLS-1$ $NON-NLS-2$ 315 | } 316 | 317 | private Class getClass(String className) { 318 | Class c = null; 319 | try { 320 | c = Class.forName(className, false, Thread.currentThread().getContextClassLoader()); 321 | } catch (ClassNotFoundException e) { 322 | try { 323 | c = Class.forName(PROTO_PREFIX + className, false, Thread.currentThread().getContextClassLoader()); 324 | } catch (ClassNotFoundException e1) { 325 | log.error("Could not find protocol class '{}'", className); //$NON-NLS-1$ 326 | } 327 | } 328 | return c; 329 | 330 | } 331 | 332 | private TCPClient getProtocol() { 333 | TCPClient tcpClient = null; 334 | Class javaClass = getClass(getClassname()); 335 | if (javaClass == null){ 336 | return null; 337 | } 338 | try { 339 | tcpClient = (TCPClient) javaClass.newInstance(); 340 | /**The EOL byte setting has higher priority, if both EOL byte & length are set, then EOL byte will be used, and length will be ignored.**/ 341 | if (getPropertyAsString(EOL_BYTE, "").length()>0){ 342 | tcpClient.setEolByte(getEolByte()); 343 | log.info("Using eolByte={}", getEolByte()); 344 | } else if (getPropertyAsString(LENGTH, "").trim().length() > 0) { 345 | tcpClient.setLength(Integer.parseInt(getPropertyAsString(LENGTH, "").trim())); 346 | log.info("Using length={}", getPropertyAsString(LENGTH, "")); 347 | } 348 | 349 | if (log.isDebugEnabled()) { 350 | log.debug("{} Created: {}@{}", this, getClassname(), Integer.toHexString(tcpClient.hashCode())); //$NON-NLS-1$ 351 | } 352 | } catch (Exception e) { 353 | log.error("{} Exception creating: {} ", this, getClassname(), e); //$NON-NLS-1$ 354 | } 355 | return tcpClient; 356 | } 357 | 358 | @Override 359 | public SampleResult sample(Entry e)// Entry tends to be ignored ... 360 | { 361 | if (firstSample) { // Do stuff we cannot do as part of threadStarted() 362 | initSampling(); 363 | firstSample=false; 364 | } 365 | final boolean reUseConnection = isReUseConnection(); 366 | final boolean closeConnection = isCloseConnection(); 367 | String socketKey = getSocketKey(); 368 | if (log.isDebugEnabled()){ 369 | log.debug(getLabel() + " " + getFilename() + " " + getUsername() + " " + getPassword()); 370 | } 371 | SampleResult res = new SampleResult(); 372 | boolean isSuccessful = false; 373 | res.setSampleLabel(getName());// Use the test element name for the label 374 | StringBuilder sb = new StringBuilder(); 375 | sb.append("Host: ").append(getServer()); // $NON-NLS-1$ 376 | sb.append(" Port: ").append(getPort()); // $NON-NLS-1$ 377 | sb.append("\n"); // $NON-NLS-1$ 378 | sb.append("Reuse: ").append(reUseConnection); // $NON-NLS-1$ 379 | sb.append(" Close: ").append(closeConnection); // $NON-NLS-1$ 380 | sb.append("\n["); // $NON-NLS-1$ 381 | sb.append("SOLINGER: ").append(getSoLinger()); // $NON-NLS-1$ 382 | sb.append(" EOL: ").append(getEolByte()); // $NON-NLS-1$ 383 | sb.append(" noDelay: ").append(getNoDelay()); // $NON-NLS-1$ 384 | sb.append("]"); // $NON-NLS-1$ 385 | res.setSamplerData(sb.toString()); 386 | res.sampleStart(); 387 | try { 388 | Socket sock; 389 | try { 390 | sock = getSocket(socketKey); 391 | } finally { 392 | res.connectEnd(); 393 | } 394 | if (sock == null) { 395 | res.setResponseCode("500"); //$NON-NLS-1$ 396 | res.setResponseMessage(getError()); 397 | } else if (protocolHandler == null){ 398 | res.setResponseCode("500"); //$NON-NLS-1$ 399 | res.setResponseMessage("Protocol handler not found"); 400 | } else { 401 | currentSocket = sock; 402 | InputStream is = sock.getInputStream(); 403 | OutputStream os = sock.getOutputStream(); 404 | String req = getRequestData(); 405 | // TODO handle filenames 406 | res.setSamplerData(req); 407 | protocolHandler.write(os, req); 408 | String in = protocolHandler.read(is, res); 409 | isSuccessful = setupSampleResult(res, in, null, protocolHandler); 410 | } 411 | } catch (ReadException ex) { 412 | log.error("", ex); 413 | isSuccessful=setupSampleResult(res, ex.getPartialResponse(), ex,protocolHandler); 414 | closeSocket(socketKey); 415 | } catch (Exception ex) { 416 | log.error("", ex); 417 | isSuccessful=setupSampleResult(res, "", ex, protocolHandler); 418 | closeSocket(socketKey); 419 | } finally { 420 | currentSocket = null; 421 | // Calculate response time 422 | res.sampleEnd(); 423 | 424 | // Set if we were successful or not 425 | res.setSuccessful(isSuccessful); 426 | 427 | if (!reUseConnection || closeConnection) { 428 | closeSocket(socketKey); 429 | } 430 | } 431 | return res; 432 | } 433 | 434 | /** 435 | * Fills SampleResult object 436 | * @param sampleResult {@link SampleResult} 437 | * @param readResponse Response read until error occurred 438 | * @param exception Source exception 439 | * @param protocolHandler {@link TCPClient} 440 | * @return boolean if sample is considered as successful 441 | */ 442 | private boolean setupSampleResult(SampleResult sampleResult, 443 | String readResponse, 444 | Exception exception, 445 | TCPClient protocolHandler) { 446 | sampleResult.setResponseData(readResponse, 447 | protocolHandler != null ? protocolHandler.getCharset() : null); 448 | sampleResult.setDataType(SampleResult.TEXT); 449 | if(exception==null) { 450 | sampleResult.setResponseCodeOK(); 451 | sampleResult.setResponseMessage("OK"); //$NON-NLS-1$ 452 | } else { 453 | sampleResult.setResponseCode("500"); //$NON-NLS-1$ 454 | sampleResult.setResponseMessage(exception.toString()); //$NON-NLS-1$ 455 | } 456 | boolean isSuccessful = exception == null; 457 | // Reset the status code if the message contains one 458 | if (!StringUtils.isEmpty(readResponse) && STATUS_PREFIX.length() > 0) { 459 | int i = readResponse.indexOf(STATUS_PREFIX); 460 | int j = readResponse.indexOf(STATUS_SUFFIX, i + STATUS_PREFIX.length()); 461 | if (i != -1 && j > i) { 462 | String rc = readResponse.substring(i + STATUS_PREFIX.length(), j); 463 | sampleResult.setResponseCode(rc); 464 | isSuccessful = isSuccessful && checkResponseCode(rc); 465 | if (HAVE_STATUS_PROPS) { 466 | sampleResult.setResponseMessage(STATUS_PROPS.getProperty(rc, "Status code not found in properties")); //$NON-NLS-1$ 467 | } else { 468 | sampleResult.setResponseMessage("No status property file"); 469 | } 470 | } else { 471 | sampleResult.setResponseCode("999"); //$NON-NLS-1$ 472 | sampleResult.setResponseMessage("Status value not found"); 473 | isSuccessful = false; 474 | } 475 | } 476 | return isSuccessful; 477 | } 478 | 479 | /** 480 | * @param rc response code 481 | * @return whether this represents success or not 482 | */ 483 | private boolean checkResponseCode(String rc) { 484 | int responseCode = Integer.parseInt(rc); 485 | return responseCode >= 400 && responseCode <= 599; 486 | } 487 | 488 | @Override 489 | public void threadStarted() { 490 | log.debug("Thread Started"); //$NON-NLS-1$ 491 | firstSample = true; 492 | } 493 | 494 | // Cannot do this as part of threadStarted() because the Config elements have not been processed. 495 | private void initSampling() { 496 | protocolHandler = getProtocol(); 497 | if (log.isDebugEnabled()) { 498 | log.debug("Using Protocol Handler: {}", //$NON-NLS-1$ 499 | protocolHandler == null ? "NONE" : protocolHandler.getClass().getName()); //$NON-NLS-1$ 500 | } 501 | if (protocolHandler != null){ 502 | protocolHandler.setupTest(); 503 | } 504 | } 505 | 506 | /** 507 | * Close socket of current sampler 508 | */ 509 | private void closeSocket(String socketKey) { 510 | Map cp = tp.get(); 511 | Socket con = (Socket) cp.remove(socketKey); 512 | if (con != null) { 513 | log.debug("{} Closing connection {}", this, con); //$NON-NLS-1$ 514 | try { 515 | con.close(); 516 | } catch (IOException e) { 517 | log.warn("Error closing socket {}", e); //$NON-NLS-1$ 518 | } 519 | } 520 | } 521 | 522 | /** 523 | * {@inheritDoc} 524 | */ 525 | @Override 526 | public void threadFinished() { 527 | log.debug("Thread Finished"); //$NON-NLS-1$ 528 | tearDown(); 529 | if (protocolHandler != null){ 530 | protocolHandler.teardownTest(); 531 | } 532 | } 533 | 534 | /** 535 | * Closes all connections, clears Map and remove thread local Map 536 | */ 537 | private void tearDown() { 538 | Map cp = tp.get(); 539 | cp.forEach((k, v) -> { 540 | if(k.startsWith(TCPKEY)) { 541 | try { 542 | ((Socket)v).close(); 543 | } catch (IOException e) { 544 | // NOOP 545 | } 546 | } 547 | }); 548 | cp.clear(); 549 | tp.remove(); 550 | } 551 | 552 | /** 553 | * @see org.apache.jmeter.samplers.AbstractSampler#applies(org.apache.jmeter.config.ConfigTestElement) 554 | */ 555 | @Override 556 | public boolean applies(ConfigTestElement configElement) { 557 | String guiClass = configElement.getProperty(TestElement.GUI_CLASS).getStringValue(); 558 | return APPLIABLE_CONFIG_CLASSES.contains(guiClass); 559 | } 560 | 561 | @Override 562 | public boolean interrupt() { 563 | Optional sock = Optional.ofNullable(currentSocket); // fetch in case gets nulled later 564 | if (sock.isPresent()) { 565 | try { 566 | sock.get().close(); 567 | } catch (IOException ignored) { 568 | // NOOP 569 | } 570 | return true; 571 | } else { 572 | return false; 573 | } 574 | } 575 | } 576 | -------------------------------------------------------------------------------- /wsocket_echo/.settings/.jsdtscope: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /wsocket_echo/.settings/org.eclipse.core.resources.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | encoding//src/main/resources=UTF-8 3 | encoding/=UTF-8 4 | -------------------------------------------------------------------------------- /wsocket_echo/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 4 | org.eclipse.jdt.core.compiler.compliance=1.7 5 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 6 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 7 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning 8 | org.eclipse.jdt.core.compiler.source=1.7 9 | -------------------------------------------------------------------------------- /wsocket_echo/.settings/org.eclipse.m2e.core.prefs: -------------------------------------------------------------------------------- 1 | activeProfiles= 2 | eclipse.preferences.version=1 3 | resolveWorkspaceProjects=true 4 | version=1 5 | -------------------------------------------------------------------------------- /wsocket_echo/.settings/org.eclipse.wst.common.component: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /wsocket_echo/.settings/org.eclipse.wst.jsdt.ui.superType.container: -------------------------------------------------------------------------------- 1 | org.eclipse.wst.jsdt.launching.baseBrowserLibrary -------------------------------------------------------------------------------- /wsocket_echo/.settings/org.eclipse.wst.jsdt.ui.superType.name: -------------------------------------------------------------------------------- 1 | Window -------------------------------------------------------------------------------- /wsocket_echo/.settings/org.eclipse.wst.validation.prefs: -------------------------------------------------------------------------------- 1 | disabled=06target 2 | eclipse.preferences.version=1 3 | -------------------------------------------------------------------------------- /wsocket_echo/main/java/net/xmeter/EchoService.java: -------------------------------------------------------------------------------- 1 | package net.xmeter; 2 | 3 | import java.io.IOException; 4 | import java.text.MessageFormat; 5 | 6 | import javax.websocket.OnError; 7 | import javax.websocket.OnMessage; 8 | import javax.websocket.OnOpen; 9 | import javax.websocket.Session; 10 | import javax.websocket.server.ServerEndpoint; 11 | 12 | 13 | @ServerEndpoint("/echo") 14 | public class EchoService { 15 | private Session session; 16 | 17 | @OnOpen 18 | public void start(Session session) { 19 | this.session = session; 20 | } 21 | 22 | public Session getSession() { 23 | return session; 24 | } 25 | 26 | @OnError 27 | public void onError(Session session, Throwable t) { 28 | System.out.println(MessageFormat.format("Find exception {0} for web-socket session {1}.", t.getMessage(), session.getId())); 29 | if(!session.isOpen()) { 30 | System.out.println(MessageFormat.format("The web-socket {0} was already closed, now is going to remove the notification listeners.", session.getId())); 31 | } 32 | } 33 | 34 | @OnMessage 35 | public void onMessage(Session session, String msg, boolean last) { 36 | try { 37 | String message = "server echo, " + msg.toString(); 38 | System.out.println(message); 39 | session.getBasicRemote().sendText(message); 40 | } catch (IOException e) { 41 | e.printStackTrace(); 42 | try { 43 | session.close(); 44 | } catch (IOException ex) { 45 | ex.printStackTrace(); 46 | } 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /wsocket_echo/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.xmeter 8 | xmeter-parent 9 | 0.0.3-SNAPSHOT 10 | 11 | net.xmeter 12 | wsocket_echo 13 | 0.0.1-SNAPSHOT 14 | war 15 | wsocket_echo Maven Webapp 16 | http://maven.apache.org 17 | 18 | 19 | junit 20 | junit 21 | 3.8.1 22 | test 23 | 24 | 25 | org.apache.tomcat 26 | tomcat-websocket-api 27 | 8.0.32 28 | provided 29 | 30 | 31 | 32 | wsocket_echo 33 | 34 | 35 | -------------------------------------------------------------------------------- /wsocket_echo/src/main/webapp/WEB-INF/web.xml: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | Archetype Created Web Application 7 | 8 | -------------------------------------------------------------------------------- /wsocket_echo/src/main/webapp/css/starter-template.css: -------------------------------------------------------------------------------- 1 | body { 2 | padding-top: 50px; 3 | } 4 | .starter-template { 5 | padding: 40px 15px; 6 | text-align: center; 7 | } -------------------------------------------------------------------------------- /wsocket_echo/src/main/webapp/wsocket_client.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Websocket sample 6 | 8 | 10 | 11 | 12 | 13 | 14 | 15 |

31 | 32 |
33 |
34 |

WebSocket 调用例子

35 |
36 | 37 | 38 | 39 | 40 |
41 |
42 | 43 |
44 |
45 | 46 | 95 | 96 | --------------------------------------------------------------------------------