Wednesday, 10 February 2016

Apache Camel Web-socket

Apache Camel Websocket


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 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

13 comments:

  1. 3C1B5C6A5BLeah40A59DBBF427 November 2024 at 03:43

    4927ED5484
    beğeni

    ReplyDelete