Vert.x WebSocket
Since Camel 3.5
Both producer and consumer are supported
The Vert.x WebSocket component provides WebSocket capabilities as a WebSocket server, or as a client to connect to an existing WebSocket.
Maven users will need to add the following dependency to their pom.xml for this component:
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-vertx-websocket</artifactId>
<version>x.x.x</version>
<!-- use the same version as your Camel core version -->
</dependency> Configuring Options
Camel components are configured on two separate levels:
-
component level
-
endpoint level
Configuring Component Options
At the component level, you set general and shared configurations that are, then, inherited by the endpoints. It is the highest configuration level.
For example, a component may have security settings, credentials for authentication, urls for network connection and so forth.
Some components only have a few options, and others may have many. Because components typically have pre-configured defaults that are commonly used, then you may often only need to configure a few options on a component; or none at all.
You can configure components using:
-
the Component DSL.
-
in a configuration file (
application.properties,*.yamlfiles, etc). -
directly in the Java code.
Configuring Endpoint Options
You usually spend more time setting up endpoints because they have many options. These options help you customize what you want the endpoint to do. The options are also categorized into whether the endpoint is used as a consumer (from), as a producer (to), or both.
Configuring endpoints is most often done directly in the endpoint URI as path and query parameters. You can also use the Endpoint DSL and DataFormat DSL as a type safe way of configuring endpoints and data formats in Java.
A good practice when configuring options is to use Property Placeholders.
Property placeholders provide a few benefits:
-
They help prevent using hardcoded urls, port numbers, sensitive information, and other settings.
-
They allow externalizing the configuration from the code.
-
They help the code to become more flexible and reusable.
The following two sections list all the options, firstly for the component followed by the endpoint.
Component Options
The Vert.x WebSocket component supports the following options which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | |
Whether the consumers route each message synchronously, as the default for the endpoints of this component. See the synchronous endpoint option. | false | boolean | |
Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | |
Whether the producer and a consumer with consumeAsClient=true add an Origin header to the WebSocket handshake request, as the default for the endpoints of this component. See the allowOriginHeader endpoint option. | true | boolean | |
Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc. | true | boolean | |
The host of an endpoint whose URI has no host, such as vertx-websocket:/chat. The default 0.0.0.0 makes the server consumer bind to all network interfaces. | 0.0.0.0 | String | |
The port of an endpoint whose URI has no port. With the default 0, the server consumer binds to a free port that the operating system picks, and the producer and a consumer with consumeAsClient=true connect to port 80, or to port 443 with TLS. | 0 | int | |
The value of the Origin header of the WebSocket handshake request, as the default for the endpoints of this component. See the originHeaderUrl endpoint option. | String | ||
The Vert.x Router that the HTTP servers of the server consumers use, unless the router option of the endpoint is set. The one router serves the HTTP servers of all hosts and ports. If not set, the Router bean of the registry is used when there is exactly one, and otherwise each HTTP server gets a new router. | Router | ||
To use an existing Vert.x instance instead of creating a new one. If not set, the component uses the Vertx bean of the registry when there is exactly one, and otherwise creates its own instance, which it closes when it stops. | Vertx | ||
The VertxOptions of the Vert.x instance that the component creates. Not used when the component uses an existing Vert.x instance, from the vertx option or a Vertx bean of the registry. | VertxOptions | ||
Whether to use the global SSL context parameters of the CamelContext for each endpoint that the component creates and that has no sslContextParameters. See the sslContextParameters endpoint option. | false | boolean |
Endpoint Options
The Vert.x WebSocket endpoint is configured using URI syntax:
vertx-websocket:host:port/path
With the following path and query parameters:
Path Parameters
| Name | Description | Default | Type |
|---|---|---|---|
Required The host name or IP address. The server consumer binds its HTTP server to it, and the producer and a consumer with consumeAsClient=true connect to it. If the URI has no host, the defaultHost option of the component is used. | String | ||
Required The port number. The server consumer binds its HTTP server to it, and with 0 to a free port that the operating system picks. The producer and a consumer with consumeAsClient=true connect to it, and with 0 to port 80, or to port 443 when the connection uses TLS. If the URI has no port, the defaultPort option of the component is used. | int | ||
The path of the WebSocket. The server consumer accepts WebSocket connections on it: the path can hold parameters such as /chat/{user}, whose values the consumer sets as headers, and can end with * to accept each path that starts with it. The producer and a consumer with consumeAsClient=true connect to it. If the URI has no path, / is used. | String |
Query Parameters
| Name | Description | Default | Type |
|---|---|---|---|
A regular expression for the Origin header of the WebSocket handshake requests that the server consumer accepts. A handshake request whose Origin header does not match is rejected with status 403. If not set, the server consumer does not check the Origin header. | String | ||
When consumeAsClient is set to true, a text message to send to the server each time the consumer connects: when it starts and after each reconnect. For example a subscribe request, for a server that only sends messages to a client that asked for them. | String | ||
Whether the consumer connects as a WebSocket client to the server at the host, port and path, instead of starting a WebSocket server, and routes each text or binary message that the server sends. The consumer fails to start if it cannot connect. When the connection is lost later, it reconnects as set by reconnectInitialDelay, reconnectInterval and maxReconnectAttempts. | false | boolean | |
Whether the server consumer also routes an exchange when a peer connects, with the event OPEN and the Vert.x ServerWebSocket as body, and when a peer disconnects, with the event CLOSE and no body. The CamelVertxWebsocket.event header holds the event. A consumer with consumeAsClient=true does not use it. | false | boolean | |
The maximum number of failed reconnect attempts of a consumer with consumeAsClient=true, counted again for each loss of the connection. When they are used up, the consumer logs a warning and stays started without a connection. With the default 0, the consumer tries to reconnect without limit. | int | ||
The delay in milliseconds from the loss of the connection to the first reconnect attempt, for a consumer with consumeAsClient=true. With the default 0, the first attempt is made at once. | int | ||
The interval in milliseconds between the reconnect attempts of a consumer with consumeAsClient=true. When an attempt is still running at the end of an interval, no other attempt starts until it ends. | 1000 | int | |
Whether the consumer routes each message synchronously. When true, the route runs on a thread of the Vert.x worker pool, which waits until the route is complete, so the size of the worker pool limits how many messages are routed at the same time. When false, the route starts on a worker thread with the asynchronous routing engine, and the worker thread is free as soon as the route continues on another thread (such as an asynchronous producer), so the worker pool no longer limits the messages in flight. Keep it false for a route that calls an asynchronous producer using the same Vert.x (such as vertx-http): with true, such messages can occupy every worker thread while their producers need a worker thread to complete, and then no message completes. | false | boolean | |
Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | |
To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored. | ExceptionHandler | ||
Sets the exchange pattern when the consumer creates an exchange. Enum values:
| ExchangePattern | ||
When consumeAsClient is set to true, whether the received messages are routed in parallel, on the threads of the Vert.x worker pool, in any order. By default (false), the messages of the WebSocket are routed one after the other, in the order they are received. | false | boolean | |
The Vert.x Router of the HTTP server of the server consumer, for example to serve other HTTP routes on the same server. All consumers on the same host and port share one HTTP server, which uses the router of the consumer that starts first. If not set, the router option of the component is used. | Router | ||
The Vert.x HttpServerOptions of the HTTP server of the server consumer. All consumers on the same host and port share one HTTP server, which uses the options of the consumer that starts first. The server listens on the host and port of the endpoint, not on those of the options. | HttpServerOptions | ||
A comma-separated list of the WebSocket subprotocols that the producer and a consumer with consumeAsClient=true request in the Sec-WebSocket-Protocol header of the handshake request. | String | ||
Whether the producer sends each message to all the peers that are connected on the path of the endpoint to a server consumer of this component with the same host name and port, instead of to a remote WebSocket server. If no peer is connected, the message is not sent. The CamelVertxWebsocket.sendToAll header replaces this option for a message. | false | boolean | |
The Vert.x WebSocketClientOptions of the WebSocket client that the producer and a consumer with consumeAsClient=true connect with. Its connect timeout also limits how long they wait for the handshake to complete. When sslContextParameters is set, its TLS settings are applied on top of these options. | WebSocketClientOptions | ||
Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | |
To use a custom HeaderFilterStrategy to filter the query and path parameters of the WebSocket handshake request, which the server consumer sets as headers of each exchange. The producer does not use it. | HeaderFilterStrategy | ||
Whether the producer and a consumer with consumeAsClient=true add an Origin header, derived from the host and port of the server, to the WebSocket handshake request. Set it to false for a server that rejects handshake requests with an Origin header. Not used when originHeaderUrl is set, as that Origin is always sent. | true | boolean | |
The HTTP headers to add to the WebSocket handshake request that the producer and a consumer with consumeAsClient=true send, such as handshake.X-Tenant=acme for an X-Tenant header. The server consumer does not use them. This is a multi-value option with prefix: handshake. | Map | ||
The value of the Origin header of the WebSocket handshake request that the producer and a consumer with consumeAsClient=true send, such as https://example.com. It is sent even when allowOriginHeader is false. If not set, the Origin is derived from the host and port of the server, unless allowOriginHeader is false. | String | ||
The TLS configuration as org.apache.camel.support.jsse.SSLContextParameters. The server consumer accepts wss connections with it, and all consumers on the same host and port must use the same instance or none, otherwise the consumer fails to start. The producer and a consumer with consumeAsClient=true connect with TLS using it. If not set and the useGlobalSslContextParameters option of the component is true, the global SSL context parameters are used. | SSLContextParameters |
Message Headers
The Vert.x WebSocket component supports the following message header(s), which is/are listed below:
| Name | Description | Default | Type |
|---|---|---|---|
CamelVertxWebsocket.connectionKey (common) Constant: | The key of a peer connected to the server consumer. The server consumer sets it to the key of the peer that the exchange comes from, a key that it creates when the peer connects. The producer sends the message to the peer with this key, or to each peer of a comma-separated list of keys, among the peers that are connected on its path to a server consumer of this component with the same host name and port. | String | |
CamelVertxWebsocket.sendToAll (producer) Constant: | Whether the producer sends the message to all the peers that are connected on its path to a server consumer of this component with the same host name and port. Replaces the sendToAll option of the endpoint for this message. | boolean | |
CamelVertxWebsocket.remoteAddress (consumer) Constant: | The address of the peer that the exchange comes from, as a Vert.x SocketAddress with its host and port. Set by the server consumer. | SocketAddress | |
CamelVertxWebsocket.event (consumer) Constant: | The event that the exchange comes from: MESSAGE for a received message, and OPEN or CLOSE for a peer that connects or disconnects when fireWebSocketConnectionEvents is true. Set by the server consumer. An exchange with the event ERROR goes to the exception handler of the consumer instead of the route. Enum values:
| VertxWebsocketEvent |
Message Body
The message body at each side of the Vert.x WebSocket component: Consumer is the body of the messages the consumer creates, Consumer reply the bodies a consumer that answers its caller can reply with, Producer input the bodies the producer can send or write, and Producer output the body after the producer.
| Side | Body | Description |
|---|---|---|
Consumer |
| The message received: a String for a text frame, a byte array for a binary frame. With fireWebSocketConnectionEvents=true, the OPEN event has the Vert.x ServerWebSocket as body and the CLOSE event no body: the CamelVertxWebsocket.event header tells them apart.
|
Producer input |
| A String is sent as a text frame and a byte array as a binary frame; any other body is converted to a String and sent as a text frame, so a stream with binary content must be converted to bytes first, and a Map or a POJO is sent as its toString: marshal it first. No body sends nothing. |
Producer output |
|
The bodies are the ones with the default options. A side that is not listed is not known, and tooling does not guess it. The carriers, the sides and the tools that use them are described in Message Body Types.
Usage
The following example shows how to expose a WebSocket on http://localhost:8080/echo and returns an 'echo' response back to the same channel:
-
Java
-
XML
-
YAML
from("vertx-websocket:localhost:8080/echo")
.transform().simple("Echo: ${body}")
.to("vertx-websocket:localhost:8080/echo"); <route>
<from uri="vertx-websocket:localhost:8080/echo"/>
<transform>
<simple>Echo: ${body}</simple>
</transform>
<to uri="vertx-websocket:localhost:8080/echo"/>
</route> - route:
from:
uri: vertx-websocket:localhost:8080/echo
steps:
- transform:
simple: "Echo: ${body}"
- to:
uri: vertx-websocket:localhost:8080/echo It’s also possible to configure the consumer to connect as a WebSocket client on a remote address with the consumeAsClient option:
-
Java
-
XML
-
YAML
from("vertx-websocket:my.websocket.com:8080/chat?consumeAsClient=true")
.log("Got WebSocket message ${body}"); <route>
<from uri="vertx-websocket:my.websocket.com:8080/chat?consumeAsClient=true"/>
<log message="Got WebSocket message ${body}"/>
</route> - route:
from:
uri: vertx-websocket:my.websocket.com:8080/chat
parameters:
consumeAsClient: true
steps:
- log:
message: "Got WebSocket message ${body}" The client consumer routes the messages of its WebSocket one after the other, in the order they are received. To route them in parallel, on the threads of the Vert.x worker pool and in any order, set parallelProcessing=true.
Some servers only send messages to a client that asked for them, such as a feed that needs a subscribe request. Set connectMessage to the text to send each time the consumer connects: when it starts and after each reconnect.
- route:
from:
uri: vertx-websocket:my.websocket.com:8080/feed
parameters:
consumeAsClient: true
connectMessage: '{"op":"subscribe","channel":"prices"}'
steps:
- log:
message: "Got WebSocket message ${body}" The query parameters of the URI that are not options of the component are sent to the remote server. Like any endpoint URI, Camel decodes the URI before the component reads it, so write a value that contains +, & or % (such as a token or a signature) as a raw value, for example token=RAW(a+b/c=). It then reaches the server as written. See raw values.
Path & query parameters
The WebSocket server consumer supports the configuration of parameterized paths. The path parameter value will be set as a Camel exchange header:
-
Java
-
XML
-
YAML
from("vertx-websocket:localhost:8080/chat/{user}")
.log("New message from ${header.user} >>> ${body}") <route>
<from uri="vertx-websocket:localhost:8080/chat/{user}"/>
<log message="New message from ${header.user} >>> ${body}"/>
</route> - route:
from:
uri: vertx-websocket:localhost:8080/chat/{user}
steps:
- log:
message: "New message from ${header.user} >>> ${body}" Similarly, you can retrieve any query parameter values used by the WebSocket client to connect to the server endpoint:
-
Java
-
XML
-
YAML
from("direct:sendChatMessage")
.to("vertx-websocket:localhost:8080/chat/camel?role=admin");
from("vertx-websocket:localhost:8080/chat/{user}")
.log("New message from ${header.user} (${header.role}) >>> ${body}") <route>
<from uri="direct:sendChatMessage"/>
<to uri="vertx-websocket:localhost:8080/chat/camel?role=admin"/>
</route>
<route>
<from uri="vertx-websocket:localhost:8080/chat/{user}"/>
<log message="New message from ${header.user} (${header.role}) >>> ${body}"/>
</route> - route:
from:
uri: direct:sendChatMessage
steps:
- to:
uri: vertx-websocket:localhost:8080/chat/camel
parameters:
role: admin
- route:
from:
uri: vertx-websocket:localhost:8080/chat/{user}
steps:
- log:
message: "New message from ${header.user} (${header.role}) >>> ${body}" A message the producer sends completes on a Vert.x event loop thread. The route then continues on a thread of the Vert.x worker pool, so a step after the producer may block (such as an HTTP call, or another vertx-websocket producer that connects to a server) without stalling the WebSocket I/O of that event loop.
Sending messages to peers connected to the vertx-websocket server consumer
| This section only applies when producing messages to a WebSocket hosted by the camel-vertx-websocket consumer. It is not relevant when producing messages to an externally hosted WebSocket. |
To send a message to all peers connected to a WebSocket hosted by the vertx-websocket server consumer, use the sendToAll=true endpoint option, or the CamelVertxWebsocket.sendToAll header.
-
Java
-
XML
-
YAML
from("vertx-websocket:localhost:8080/chat")
.log("Got WebSocket message ${body}");
from("direct:broadcastMessage")
.setBody().constant("This is a broadcast message!")
.to("vertx-websocket:localhost:8080/chat?sendToAll=true"); <route>
<from uri="vertx-websocket:localhost:8080/chat"/>
<log message="Got WebSocket message ${body}"/>
</route>
<route>
<from uri="direct:broadcastMessage"/>
<setBody>
<constant>This is a broadcast message!</constant>
</setBody>
<to uri="vertx-websocket:localhost:8080/chat?sendToAll=true"/>
</route> - route:
from:
uri: vertx-websocket:localhost:8080/chat
steps:
- log:
message: "Got WebSocket message ${body}"
- route:
from:
uri: direct:broadcastMessage
steps:
- setBody:
constant: "This is a broadcast message!"
- to:
uri: vertx-websocket:localhost:8080/chat
parameters:
sendToAll: true Alternatively, you can send messages to specific peers by using the CamelVertxWebsocket.connectionKey header. Multiple peers can be specified as a comma separated list.
The value of the connectionKey can be determined whenever a peer triggers an event on the vertx-websocket consumer, where a unique key identifying the peer will be propagated via the CamelVertxWebsocket.connectionKey header.
-
Java
-
XML
-
YAML
from("vertx-websocket:localhost:8080/chat")
.log("Got WebSocket message ${body}");
from("direct:broadcastMessage")
.setBody().constant("This is a broadcast message!")
.setHeader("CamelVertxWebsocket.connectionKey").constant("key-1,key-2,key-3")
.to("vertx-websocket:localhost:8080/chat"); <route>
<from uri="vertx-websocket:localhost:8080/chat"/>
<log message="Got WebSocket message ${body}"/>
</route>
<route>
<from uri="direct:broadcastMessage"/>
<setBody>
<constant>This is a broadcast message!</constant>
</setBody>
<setHeader name="CamelVertxWebsocket.connectionKey">
<constant>key-1,key-2,key-3</constant>
</setHeader>
<to uri="vertx-websocket:localhost:8080/chat"/>
</route> - route:
from:
uri: vertx-websocket:localhost:8080/chat
steps:
- log:
message: "Got WebSocket message ${body}"
- route:
from:
uri: direct:broadcastMessage
steps:
- setBody:
constant: "This is a broadcast message!"
- setHeader:
name: CamelVertxWebsocket.connectionKey
constant: "key-1,key-2,key-3"
- to:
uri: vertx-websocket:localhost:8080/chat SSL
By default, the ws:// protocol is used, but secure connections with wss:// are supported by configuring the consumer or producer via the sslContextParameters URI parameter and the Camel JSSE Configuration Utility
All consumers on the same host and port are served by one HTTP server, so they must use the same sslContextParameters instance. A consumer whose sslContextParameters differ from those of the consumers already started on its host and port fails to start.
Vert.x creates its own TLS engine from the sslContextParameters: the key and trust managers, the client authentication, the cipher suites, the protocols and the named groups (including the post-quantum preference of SSLContextParameters) are applied. Vert.x has no setting for the signature schemes, which are not applied, and a WARN is logged when they are configured.