public interface WebSocket extends Closeable, Registry
Creating web sockets is pretty straightforward:
{ ws("/", (ws) -> { // connected ws.onMessage(message -> { System.out.println(message.value()); ws.send("Message Received"); }); ws.send("Connected"); }); }First thing you need to do is to register a new web socket in your App using the
Router.ws(String, WebSocket.OnOpen1)
method. You can specify a path to listen for web socket connection. The path can be a static path or a path pattern (like routes). On new connections the WebSocket.OnOpen1.onOpen(WebSocket)
will be executed from there you can listen using the onMessage(OnMessage)
, onClose(OnClose)
or onError(OnError)
events. Inside a handler you can send text or binary message.
Starting from 1.1.0
is it possible to use a class as web socket listener (in addition to the script web sockets supported). Your class must implement onMessage(OnMessage)
, like:
@Path("/ws")
class MyHandler implements WebSocket.OnMessage<String> {
private WebSocket ws;
@Inject
public MyHandler(WebSocket ws) {
this.ws = ws;
}
@Override
public void onMessage(String message) {
ws.send("Got it!");
}
}
{
ws(MyHandler.class);
}
Optionally, your listener might implements the WebSocket.OnClose
, WebSocket.OnError
or WebSocket.OnOpen
callbacks. Or if you want to implement all them, then just WebSocket.Handler
If your web socket is suppose to send/received a specific data type, like: json
it is nice to define a consume and produce types:
ws("/", (ws) -> { ws.onMessage(message -> { // read as json MyObject object = message.to(MyObject.class); }); MyObject object = new MyObject(); ws.send(object); // convert to text message using a json converter }) .consumes(MediaType.json) .produces(MediaType.json);
Or via annotations for mvc listeners:
@Consumes("json")
@Produces("json")
@Path("/ws")
class MyHandler implements WebSocket.OnMessage<MyObject> {
public void onMessage(MyObject message) {
// ...
ws.send(new ResponseObject());
}
}
The message MyObject
will be processed by a json
parser and the response object will be renderered as json too.
Modifier and Type | Interface and Description |
---|---|
static class |
WebSocket.CloseStatus
Hold a status code and optionally a reason message for close() operations.
|
static class |
WebSocket.Definition
Configure a web socket.
|
static interface |
WebSocket.Handler<T> |
static interface |
WebSocket.OnClose |
static interface |
WebSocket.OnError
Web socket err callback.
|
static interface |
WebSocket.OnMessage<T>
Web socket message callback.
|
static interface |
WebSocket.OnOpen
A web socket connect handler.
|
static interface |
WebSocket.OnOpen1
A web socket connect handler.
|
static interface |
WebSocket.SuccessCallback
Web socket success callback.
|
Modifier and Type | Field and Description |
---|---|
static WebSocket.CloseStatus |
BAD_DATA
"1007 indicates that an endpoint is terminating the connection because it has received data within a message that was not consistent with the type of the message (e.g., non-UTF-8 [RFC3629] data within a text message)."
|
static WebSocket.OnError |
ERR
Default err callback.
|
static WebSocket.CloseStatus |
GOING_AWAY
"1001 indicates that an endpoint is "going away", such as a server going down or a browser having navigated away from a page."
|
static com.google.inject.Key<Set<WebSocket.Definition>> |
KEY
Websocket key.
|
static WebSocket.CloseStatus |
NORMAL
"1000 indicates a normal closure, meaning that the purpose for which the connection was established has been fulfilled."
|
static WebSocket.CloseStatus |
NOT_ACCEPTABLE
"1003 indicates that an endpoint is terminating the connection because it has received a type of data it cannot accept (e.g., an endpoint that understands only text data MAY send this if it receives a binary message)."
|
static WebSocket.CloseStatus |
POLICY_VIOLATION
"1008 indicates that an endpoint is terminating the connection because it has received a message that violates its policy.
|
static WebSocket.CloseStatus |
PROTOCOL_ERROR
"1002 indicates that an endpoint is terminating the connection due to a protocol error."
|
static WebSocket.CloseStatus |
REQUIRED_EXTENSION
"1010 indicates that an endpoint (client) is terminating the connection because it has expected the server to negotiate one or more extension, but the server didn't return them in the response message of the WebSocket handshake.
|
static WebSocket.CloseStatus |
SERVER_ERROR
"1011 indicates that a server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request."
|
static WebSocket.CloseStatus |
SERVICE_OVERLOAD
"1013 indicates that the service is experiencing overload.
|
static WebSocket.CloseStatus |
SERVICE_RESTARTED
"1012 indicates that the service is restarted.
|
static WebSocket.SuccessCallback |
SUCCESS
Default success callback.
|
static WebSocket.CloseStatus |
TOO_BIG_TO_PROCESS
"1009 indicates that an endpoint is terminating the connection because it has received a message that is too big for it to process."
|
Modifier and Type | Method and Description |
---|---|
Map<String,Object> |
attributes()
Web socket attributes.
|
default void |
broadcast(Object data)
Send data to all connected sessions.
|
default void |
broadcast(Object data, WebSocket.OnError err)
Send data to all connected sessions.
|
default void |
broadcast(Object data, WebSocket.SuccessCallback success)
Send data to all connected sessions.
|
void |
broadcast(Object data, WebSocket.SuccessCallback success, WebSocket.OnError err)
Send data to all connected sessions.
|
default void |
close()
Gracefully closes the connection, after sending a description message
|
default void |
close(int code)
Gracefully closes the connection, after sending a description message
|
default void |
close(int code, String reason)
Gracefully closes the connection, after sending a description message
|
void |
close(WebSocket.CloseStatus status)
Gracefully closes the connection, after sending a description message
|
MediaType |
consumes() |
<T> T |
get(String name)
Get a web socket attribute.
|
<T> Optional<T> |
ifGet(String name)
Get a web socket attribute or empty value.
|
boolean |
isOpen()
True if the websocket is still open.
|
void |
onClose(WebSocket.OnClose callback)
Register an close callback to execute when client close the web socket.
|
void |
onError(WebSocket.OnError callback)
Register an error callback to execute when an error is found.
|
void |
onMessage(WebSocket.OnMessage<Mutant> callback)
Register a callback to execute when a new message arrive.
|
String |
path() |
String |
pattern() |
void |
pause()
Pause the client stream.
|
MediaType |
produces() |
void |
resume()
Resume the client stream.
|
default void |
send(Object data)
Send data through the connection.
|
default void |
send(Object data, WebSocket.OnError err)
Send data through the connection.
|
default void |
send(Object data, WebSocket.SuccessCallback success)
Send data through the connection.
|
void |
send(Object data, WebSocket.SuccessCallback success, WebSocket.OnError err)
Send data through the connection.
|
WebSocket |
set(String name, Object value)
Set a web socket attribute.
|
void |
terminate()
Immediately shuts down the connection.
|
WebSocket |
unset()
Clear/reset all the web socket attributes.
|
<T> Optional<T> |
unset(String name)
Clear/remove a web socket attribute.
|
Map<Object,String> |
vars() |
static final com.google.inject.Key<Set<WebSocket.Definition>> KEY
static final WebSocket.SuccessCallback SUCCESS
static final WebSocket.OnError ERR
static final WebSocket.CloseStatus NORMAL
static final WebSocket.CloseStatus GOING_AWAY
static final WebSocket.CloseStatus PROTOCOL_ERROR
static final WebSocket.CloseStatus NOT_ACCEPTABLE
static final WebSocket.CloseStatus BAD_DATA
static final WebSocket.CloseStatus POLICY_VIOLATION
static final WebSocket.CloseStatus TOO_BIG_TO_PROCESS
static final WebSocket.CloseStatus REQUIRED_EXTENSION
static final WebSocket.CloseStatus SERVER_ERROR
static final WebSocket.CloseStatus SERVICE_RESTARTED
static final WebSocket.CloseStatus SERVICE_OVERLOAD
@Nonnull MediaType consumes()
* / *
.
@Nonnull MediaType produces()
* / *
.
void onMessage(WebSocket.OnMessage<Mutant> callback) throws Exception
callback
- A callback
Exception
- If something goes wrong.
void onError(WebSocket.OnError callback)
callback
- A callback
void onClose(WebSocket.OnClose callback) throws Exception
callback
- A callback
Exception
- If something goes wrong.
default void close(int code, String reason)
code
- Close status code.
reason
- Close reason.
default void close(int code)
code
- Close status code.
default void close()
close
in interface AutoCloseable
close
in interface Closeable
boolean isOpen()
void close(WebSocket.CloseStatus status)
status
- Close status code.
void resume()
void pause()
void terminate() throws Exception
Exception
- If something goes wrong.
default void send(Object data) throws Exception
Err
with NORMAL
close status.
data
- Data to send.
Exception
- If something goes wrong.
default void send(Object data, WebSocket.SuccessCallback success) throws Exception
Err
with NORMAL
close status.
data
- Data to send.
success
- A success callback.
Exception
- If something goes wrong.
default void send(Object data, WebSocket.OnError err) throws Exception
Err
with NORMAL
close status.
data
- Data to send.
err
- An err callback.
Exception
- If something goes wrong.
void send(Object data, WebSocket.SuccessCallback success, WebSocket.OnError err) throws Exception
Err
with NORMAL
close status.
data
- Data to send.
success
- A success callback.
err
- An err callback.
Exception
- If something goes wrong.
default void broadcast(Object data) throws Exception
Err
with NORMAL
close status.
data
- Data to send.
Exception
- If something goes wrong.
default void broadcast(Object data, WebSocket.SuccessCallback success) throws Exception
Err
with NORMAL
close status.
data
- Data to send.
success
- A success callback.
Exception
- If something goes wrong.
default void broadcast(Object data, WebSocket.OnError err) throws Exception
Err
with NORMAL
close status.
data
- Data to send.
err
- An err callback.
Exception
- If something goes wrong.
void broadcast(Object data, WebSocket.SuccessCallback success, WebSocket.OnError err) throws Exception
Err
with NORMAL
close status.
data
- Data to send.
success
- A success callback.
err
- An err callback.
Exception
- If something goes wrong.
@Nullable WebSocket set(String name, Object value)
name
- Attribute name.
value
- Attribute value.
<T> T get(String name)
name
- Attribute name.
<T> Optional<T> ifGet(String name)
T
- Attribute type.
name
- Attribute name.
<T> Optional<T> unset(String name)
T
- Attribute type.
name
- Attribute name.
WebSocket unset()
Copyright © 2019. All rights reserved.