Websocket Component

Table of Contents

URI format
Websocket Options
Message Headers
Usage
Setting up SSL for WebSocket Component
See Also

Available as of Camel 2.10

The websocket component provides websocket endpoints for communicating with clients using websocket. The component uses Eclipse Jetty Server which implements the IETF specification (drafts and RFC 6455). It supports the protocols ws:// and wss://. To use wss:// protocol, the SSLContextParameters must be defined.

Version currently supported

Camel 2.18 uses Jetty 9

URI format

websocket://hostname[:port][/resourceUri][?options]

You can append query options to the URI in the following format, ?option=value&option=value&…​

Websocket Options

The Jetty Websocket component supports 12 options which are listed below.

{% raw %}

NameJava TypeDescription

staticResources

String

Set a resource path for static resources (such as .html files etc). The resources can be loaded from classpath if you prefix with classpath: otherwise the resources is loaded from file system or from JAR files. For example to load from root classpath use classpath:. or classpath:WEB-INF/static If not configured (eg null) then no static resource is in use.

host

String

The hostname. The default value is 0.0.0.0

port

Integer

The port number. The default value is 9292

sslKeyPassword

String

The password for the keystore when using SSL.

sslPassword

String

The password when using SSL.

sslKeystore

String

The path to the keystore.

enableJmx

boolean

If this option is true Jetty JMX support will be enabled for this endpoint. See Jetty JMX support for more details.

minThreads

Integer

To set a value for minimum number of threads in server thread pool. MaxThreads/minThreads or threadPool fields are required due to switch to Jetty9. The default values for minThreads is 1.

maxThreads

Integer

To set a value for maximum number of threads in server thread pool. MaxThreads/minThreads or threadPool fields are required due to switch to Jetty9. The default values for maxThreads is 1 2 noCores.

threadPool

ThreadPool

To use a custom thread pool for the server. MaxThreads/minThreads or threadPool fields are required due to switch to Jetty9.

sslContextParameters

SSLContextParameters

To configure security using SSLContextParameters

socketFactory

Map

To configure a map which contains custom WebSocketFactory for sub protocols. The key in the map is the sub protocol. The default key is reserved for the default implementation.

{% endraw %}

The Jetty Websocket component supports 21 endpoint options which are listed below:

{% raw %}

NameGroupDefaultJava TypeDescription

host

common

0.0.0.0

String

The hostname. The default value is 0.0.0.0. Setting this option on the component will use the component configured value as default.

port

common

9292

Integer

The port number. The default value is 9292. Setting this option on the component will use the component configured value as default.

resourceUri

common

 

String

Required Name of the websocket channel to use

maxBinaryMessageSize

common

-1

Integer

Can be used to set the size in bytes that the websocket created by the websocketServlet may be accept before closing. (Default is -1 - or unlimited)

bridgeErrorHandler

consumer

false

boolean

Allows for bridging the consumer to the Camel routing Error Handler which mean any exceptions occurred while the consumer is trying to pickup incoming messages or the likes will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions that will be logged at WARN/ERROR level and ignored.

sessionSupport

consumer

false

boolean

Whether to enable session support which enables HttpSession for each http request.

staticResources

consumer

 

String

Set a resource path for static resources (such as .html files etc). The resources can be loaded from classpath if you prefix with classpath: otherwise the resources is loaded from file system or from JAR files. For example to load from root classpath use classpath:. or classpath:WEB-INF/static If not configured (eg null) then no static resource is in use.

exceptionHandler

consumer (advanced)

 

ExceptionHandler

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this options is not in use. By default the consumer will deal with exceptions that will be logged at WARN/ERROR level and ignored.

exchangePattern

consumer (advanced)

 

ExchangePattern

Sets the exchange pattern when the consumer creates an exchange.

sendTimeout

producer

30000

Integer

Timeout in millis when sending to a websocket channel. The default timeout is 30000 (30 seconds).

sendToAll

producer

 

Boolean

To send to all websocket subscribers. Can be used to configure on endpoint level instead of having to use the WebsocketConstants.SEND_TO_ALL header on the message.

bufferSize

advanced

8192

Integer

Set the buffer size of the websocketServlet which is also the max frame byte size (default 8192)

maxIdleTime

advanced

300000

Integer

Set the time in ms that the websocket created by the websocketServlet may be idle before closing. (default is 300000)

maxTextMessageSize

advanced

 

Integer

Can be used to set the size in characters that the websocket created by the websocketServlet may be accept before closing.

minVersion

advanced

13

Integer

Can be used to set the minimum protocol version accepted for the websocketServlet. (Default 13 - the RFC6455 version)

synchronous

advanced

false

boolean

Sets whether synchronous processing should be strictly used or Camel is allowed to use asynchronous processing (if supported).

allowedOrigins

cors

 

String

The CORS allowed origins. Use to allow all.

crossOriginFilterOn

cors

false

boolean

Whether to enable CORS

filterPath

cors

 

String

Context path for filtering CORS

enableJmx

monitoring

false

boolean

If this option is true Jetty JMX support will be enabled for this endpoint. See Jetty JMX support for more details.

sslContextParameters

security

 

SSLContextParameters

To configure security using SSLContextParameters

{% endraw %}

 

Message Headers

The websocket component uses 2 headers to indicate to either send messages back to a single/current client, or to all clients.

WebsocketConstants.SEND_TO_ALLSends the message to all clients which are currently connected. You can use the sendToAll option on the endpoint instead of using this header.

WebsocketConstants.CONNECTION_KEY

Sends the message to the client with the given connection key.

Usage

In this example we let Camel exposes a websocket server which clients can communicate with. The websocket server uses the default host and port, which would be 0.0.0.0:9292. The example will send back an echo of the input. To send back a message, we need to send the transformed message to the same endpoint "websocket://echo". This is needed because by default the messaging is InOnly.

This example is part of an unit test, which you can find here. As a client we use the AHC library which offers support for web socket as well.

Here is another example where webapp resources location have been defined to allow the Jetty Application Server to not only register the WebSocket servlet but also to expose web resources for the browser. Resources should be defined under the webapp directory.

from("activemq:topic:newsTopic")
   .routeId("fromJMStoWebSocket")
   .to("websocket://localhost:8443/newsTopic?sendToAll=true&staticResources=classpath:webapp");

Setting up SSL for WebSocket Component

Using the JSSE Configuration Utility

As of Camel 2.10, the WebSocket component supports SSL/TLS configuration through the Camel JSSE Configuration Utility.  This utility greatly decreases the amount of component specific code you need to write and is configurable at the endpoint and component levels.  The following examples demonstrate how to use the utility with the Cometd component.

Programmatic configuration of the component

KeyStoreParameters ksp = new KeyStoreParameters();
ksp.setResource("/users/home/server/keystore.jks");
ksp.setPassword("keystorePassword");

KeyManagersParameters kmp = new KeyManagersParameters();
kmp.setKeyStore(ksp);
kmp.setKeyPassword("keyPassword");

TrustManagersParameters tmp = new TrustManagersParameters();
tmp.setKeyStore(ksp);

SSLContextParameters scp = new SSLContextParameters();
scp.setKeyManagers(kmp);
scp.setTrustManagers(tmp);

CometdComponent commetdComponent = getContext().getComponent("cometds", CometdComponent.class);
commetdComponent.setSslContextParameters(scp);

Spring DSL based configuration of endpoint

...
  <camel:sslContextParameters
      id="sslContextParameters">
    <camel:keyManagers
        keyPassword="keyPassword">
      <camel:keyStore
          resource="/users/home/server/keystore.jks"
          password="keystorePassword"/>
    </camel:keyManagers>
    <camel:trustManagers>
      <camel:keyStore
          resource="/users/home/server/keystore.jks"
          password="keystorePassword"/>
    </camel:trustManagers>
  </camel:sslContextParameters>...
...
  <to uri="websocket://127.0.0.1:8443/test?sslContextParameters=#sslContextParameters"/>...

Java DSL based configuration of endpoint

...
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            public void configure() {

                String uri = "websocket://127.0.0.1:8443/test?sslContextParameters=#sslContextParameters";

                from(uri)
                     .log(">>> Message received from WebSocket Client : ${body}")
                     .to("mock:client")
                     .loop(10)
                         .setBody().constant(">> Welcome on board!")
                         .to(uri);
...

See Also