This example provides sample camel routes for WebSocket producer and consumer.
Apache camel websocket producer example:
from("direct:Producer1").
//we will use this connectionKey for uniquely identifying each connection from the client.
setHeader(WebsocketConstants.CONNECTION_KEY, header("connectionKey")).
to("websocket://{host}:{port}/camel-websocket?sendToAll=false").end();
Apache camel WebSocket consumer example.
from("direct:Consumer1")
.process(new Processor() {
public void process(Exchange exchange) throws Exception {
Map<String, Object> headers=exchange.getIn().getHeaders();
//you can get a unique connection key from the exchange header.This would be unique for each client.
//store this key somewhere, to send messages to particular client.
String uniqueConnectionKey=headers.get("websocket.connectionKey").toString();
//you can get message from the client like below.
String dataFromClient=exchange.getIn().getBody().toString();
}
}).end();
To send a message to WebSocket producer.
using producer template, we can send messages to camel WebSocket endpoint.
CamelContext camelContext=new DefaultCamelContext();
ProducerTemplate template=camelContext.createProducerTemplate();
template.sendBodyAndHeader("direct:Producer1", {message}, "connectionKey", {connectionkey});
direct:Producer1 : producer endpoint name
connectionkey : a unique connection key, which you will get from the exchange header in WebSocket consumer.
message : message to the WebSocket endpoint.
I hope this would help.
cheers
Apache camel websocket producer example:
from("direct:Producer1").
//we will use this connectionKey for uniquely identifying each connection from the client.
setHeader(WebsocketConstants.CONNECTION_KEY, header("connectionKey")).
to("websocket://{host}:{port}/camel-websocket?sendToAll=false").end();
Apache camel WebSocket consumer example.
from("direct:Consumer1")
.process(new Processor() {
public void process(Exchange exchange) throws Exception {
Map<String, Object> headers=exchange.getIn().getHeaders();
//you can get a unique connection key from the exchange header.This would be unique for each client.
//store this key somewhere, to send messages to particular client.
String uniqueConnectionKey=headers.get("websocket.connectionKey").toString();
//you can get message from the client like below.
String dataFromClient=exchange.getIn().getBody().toString();
}
}).end();
To send a message to WebSocket producer.
using producer template, we can send messages to camel WebSocket endpoint.
CamelContext camelContext=new DefaultCamelContext();
ProducerTemplate template=camelContext.createProducerTemplate();
template.sendBodyAndHeader("direct:Producer1", {message}, "connectionKey", {connectionkey});
direct:Producer1 : producer endpoint name
connectionkey : a unique connection key, which you will get from the exchange header in WebSocket consumer.
message : message to the WebSocket endpoint.
I hope this would help.
cheers