Debian Codegraph @

jetty-core/jetty-websocket/jetty-websocket-jetty-client/src/test/java/examples/SimpleEchoSocket.java

raw
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.util.concurrent.CountDownLatch;
17 import java.util.concurrent.TimeUnit;
18
19 import org.eclipse.jetty.websocket.api.Callback;
20 import org.eclipse.jetty.websocket.api.Session;
21 import org.eclipse.jetty.websocket.api.StatusCode;
22 import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose;
23 import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;
24 import org.eclipse.jetty.websocket.api.annotations.OnWebSocketOpen;
25 import org.eclipse.jetty.websocket.api.annotations.WebSocket;
26
27 /**
28 * Basic Echo Client Socket
29 */
30 @WebSocket
31 public class SimpleEchoSocket
32 {
33 private final CountDownLatch closeLatch;
34
35 public SimpleEchoSocket()
36 {
37 this.closeLatch = new CountDownLatch(1);
38 }
39
40 public boolean awaitClose(int duration, TimeUnit unit) throws InterruptedException
41 {
42 return this.closeLatch.await(duration, unit);
43 }
44
45 @OnWebSocketClose
46 public void onClose(int statusCode, String reason)
47 {
48 System.out.printf("Connection closed: %d - %s%n", statusCode, reason);
49 this.closeLatch.countDown(); // trigger latch
50 }
51
52 @OnWebSocketOpen
53 public void onOpen(Session session)
54 {
55 System.out.printf("Open: %s%n", session);
56 session.setMaxTextMessageSize(64 * 1024);
57 try
58 {
59 session.sendText("Hello", Callback.NOOP);
60 session.sendText("Thanks for the conversation.", Callback.NOOP);
61 session.close(StatusCode.NORMAL, "I'm done", Callback.NOOP);
62 }
63 catch (Throwable t)
64 {
65 t.printStackTrace();
66 }
67 }
68
69 @OnWebSocketMessage
70 public void onMessage(String msg)
71 {
72 System.out.printf("Got msg: %s%n", msg);
73 }
74 }