Debian Codegraph @

jetty-ee9/jetty-ee9-websocket/jetty-ee9-websocket-jetty-client/src/test/java/examples/ClientDemo.java

raw symbols SCIP
1 //
2 // ========================================================================
3 // Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others.
4 //
5 // This program and the accompanying materials are made available under the
6 // terms of the Eclipse Public License v. 2.0 which is available at
7 // https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
8 // which is available at https://www.apache.org/licenses/LICENSE-2.0.
9 //
10 // SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
11 // ========================================================================
12 //
13
14 package examples;
15
16 import java.net.InetSocketAddress;
17 import java.net.URI;
18 import java.nio.charset.StandardCharsets;
19 import java.time.Duration;
20 import java.util.Arrays;
21 import java.util.Random;
22 import java.util.concurrent.TimeUnit;
23 import java.util.concurrent.atomic.AtomicInteger;
24 import java.util.concurrent.atomic.AtomicLong;
25
26 import org.eclipse.jetty.ee9.websocket.api.Session;
27 import org.eclipse.jetty.ee9.websocket.api.WebSocketAdapter;
28 import org.eclipse.jetty.ee9.websocket.client.ClientUpgradeRequest;
29 import org.eclipse.jetty.ee9.websocket.client.WebSocketClient;
30 import org.eclipse.jetty.websocket.core.OpCode;
31
32 /**
33 * This is not a general purpose websocket client.
34 * <p>
35 * It's only for testing the websocket server and is hardwired to a specific draft version of the protocol.
36 * </p>
37 */
38 public class ClientDemo
39 {
40 public class TestSocket extends WebSocketAdapter
41 {
42 @Override
43 public void onWebSocketBinary(byte[] payload, int offset, int len)
44 {
45 }
46
47 @Override
48 public void onWebSocketClose(int statusCode, String reason)
49 {
50 super.onWebSocketClose(statusCode, reason);
51 }
52
53 @Override
54 public void onWebSocketConnect(Session session)
55 {
56 if (verbose)
57 {
58 System.err.printf("%s#onWebSocketConnect %s %s\n", this.getClass().getSimpleName(), session, session.getClass().getSimpleName());
59 }
60 }
61
62 public void send(byte op, byte[] data, int maxFragmentLength)
63 {
64 int off = 0;
65 int len = data.length;
66 if ((maxFragmentLength > 0) && (len > maxFragmentLength))
67 {
68 len = maxFragmentLength;
69 }
70 messagesSent++;
71 while (off < data.length)
72 {
73 framesSent++;
74
75 off += len;
76 if ((data.length - off) > len)
77 {
78 len = data.length - off;
79 }
80 if ((maxFragmentLength > 0) && (len > maxFragmentLength))
81 {
82 len = maxFragmentLength;
83 }
84 }
85 }
86 }
87
88 private static boolean verbose = false;
89
90 private static final Random RANDOM = new Random();
91
92 private final String host;
93 private final int port;
94 private final String protocol;
95 private final int timeout;
96
97 private static int framesSent;
98 private static int messagesSent;
99 private static AtomicInteger framesReceived = new AtomicInteger();
100 private static AtomicInteger messagesReceived = new AtomicInteger();
101
102 private static AtomicLong totalTime = new AtomicLong();
103 private static AtomicLong minDuration = new AtomicLong(Long.MAX_VALUE);
104 private static AtomicLong maxDuration = new AtomicLong(Long.MIN_VALUE);
105 private static long start;
106
107 public static void main(String[] args) throws Exception
108 {
109 String host = "localhost";
110 int port = 8080;
111 String protocol = null;
112 int count = 10;
113 int size = 64;
114 int fragment = 4000;
115 boolean binary = false;
116 int clients = 1;
117 int delay = 1000;
118
119 for (int i = 0; i < args.length; i++)
120 {
121 String a = args[i];
122 if ("-p".equals(a) || "--port".equals(a))
123 {
124 port = Integer.parseInt(args[++i]);
125 }
126 else if ("-h".equals(a) || "--host".equals(a))
127 {
128 host = args[++i];
129 }
130 else if ("-c".equals(a) || "--count".equals(a))
131 {
132 count = Integer.parseInt(args[++i]);
133 }
134 else if ("-s".equals(a) || "--size".equals(a))
135 {
136 size = Integer.parseInt(args[++i]);
137 }
138 else if ("-f".equals(a) || "--fragment".equals(a))
139 {
140 fragment = Integer.parseInt(args[++i]);
141 }
142 else if ("-P".equals(a) || "--protocol".equals(a))
143 {
144 protocol = args[++i];
145 }
146 else if ("-v".equals(a) || "--verbose".equals(a))
147 {
148 verbose = true;
149 }
150 else if ("-b".equals(a) || "--binary".equals(a))
151 {
152 binary = true;
153 }
154 else if ("-C".equals(a) || "--clients".equals(a))
155 {
156 clients = Integer.parseInt(args[++i]);
157 }
158 else if ("-d".equals(a) || "--delay".equals(a))
159 {
160 delay = Integer.parseInt(args[++i]);
161 }
162 else if (a.startsWith("-"))
163 {
164 usage(args);
165 }
166 }
167
168 ClientDemo[] client = new ClientDemo[clients];
169 WebSocketClient wsclient = new WebSocketClient();
170 try
171 {
172 wsclient.start();
173 start = System.currentTimeMillis();
174 protocol = protocol == null ? "echo" : protocol;
175
176 for (int i = 0; i < clients; i++)
177 {
178 client[i] = new ClientDemo(wsclient, host, port, protocol, 60000);
179 client[i].open();
180 }
181
182 System.out
183 .println("Jetty WebSocket PING " + host + ":" + port + " (" + new InetSocketAddress(host, port) + ") " + clients + " clients " + protocol);
184
185 for (int p = 0; p < count; p++)
186 {
187 long next = System.currentTimeMillis() + delay;
188
189 byte op = OpCode.TEXT;
190 if (binary)
191 {
192 op = OpCode.BINARY;
193 }
194
195 byte[] data = null;
196
197 switch (op)
198 {
199 case OpCode.TEXT:
200 {
201 StringBuilder b = new StringBuilder();
202 while (b.length() < size)
203 {
204 b.append('A' + RANDOM.nextInt(26));
205 }
206 data = b.toString().getBytes(StandardCharsets.UTF_8);
207 break;
208 }
209 case OpCode.BINARY:
210 {
211 data = new byte[size];
212 RANDOM.nextBytes(data);
213 break;
214 }
215 }
216
217 for (int i = 0; i < clients; i++)
218 {
219 client[i].send(op, data, fragment);
220 }
221
222 while (System.currentTimeMillis() < next)
223 {
224 Thread.sleep(10);
225 }
226 }
227 }
228 finally
229 {
230 for (int i = 0; i < clients; i++)
231 {
232 if (client[i] != null)
233 {
234 client[i].disconnect();
235 }
236 }
237
238 long duration = System.currentTimeMillis() - start;
239 System.out.println("--- " + host + " websocket ping statistics using " + clients + " connection" + (clients > 1 ? "s" : "") + " ---");
240 System.out.printf("%d/%d frames sent/recv, %d/%d mesg sent/recv, time %dms %dm/s %.2fbps%n", framesSent, framesReceived.get(), messagesSent,
241 messagesReceived.get(), duration, ((1000L * messagesReceived.get()) / duration),
242 (1000.0D * messagesReceived.get() * 8 * size) / duration / 1024 / 1024);
243 System.out.printf("rtt min/ave/max = %.3f/%.3f/%.3f ms\n", minDuration.get() / 1000000.0,
244 messagesReceived.get() == 0 ? 0.0 : (totalTime.get() / messagesReceived.get() / 1000000.0), maxDuration.get() / 1000000.0);
245
246 wsclient.stop();
247 }
248 }
249
250 private static void usage(String[] args)
251 {
252 System.err.println("ERROR: " + Arrays.asList(args));
253 System.err.println("USAGE: java -cp CLASSPATH " + ClientDemo.class + " [ OPTIONS ]");
254 System.err.println(" -h|--host HOST (default localhost)");
255 System.err.println(" -p|--port PORT (default 8080)");
256 System.err.println(" -b|--binary");
257 System.err.println(" -v|--verbose");
258 System.err.println(" -c|--count n (default 10)");
259 System.err.println(" -s|--size n (default 64)");
260 System.err.println(" -f|--fragment n (default 4000) ");
261 System.err.println(" -P|--protocol echo|echo-assemble|echo-fragment|echo-broadcast");
262 System.err.println(" -C|--clients n (default 1) ");
263 System.err.println(" -d|--delay n (default 1000ms) ");
264 System.exit(1);
265 }
266
267 private WebSocketClient client;
268 private TestSocket socket;
269
270 public ClientDemo(WebSocketClient client, String host, int port, String protocol, int timeoutMS) throws Exception
271 {
272 this.client = client;
273 this.host = host;
274 this.port = port;
275 this.protocol = protocol;
276 timeout = timeoutMS;
277 }
278
279 private void disconnect()
280 {
281 // TODO Auto-generated method stub
282 }
283
284 private void open() throws Exception
285 {
286 client.setIdleTimeout(Duration.ofMillis(timeout));
287 ClientUpgradeRequest request = new ClientUpgradeRequest();
288 request.setSubProtocols(protocol);
289 socket = new TestSocket();
290 URI wsUri = new URI("ws://" + host + ":" + port + "/");
291 client.connect(socket, wsUri, request).get(10, TimeUnit.SECONDS);
292 }
293
294 private void send(byte op, byte[] data, int fragment)
295 {
296 socket.send(op, data, fragment);
297 }
298 }