Skip to content

Commit

Permalink
Fix #27 - Document web sockets.
Browse files Browse the repository at this point in the history
Signed-off-by: Clement Escoffier <[email protected]>
  • Loading branch information
cescoffier committed Apr 15, 2014
1 parent 1de4462 commit 354ba1a
Show file tree
Hide file tree
Showing 4 changed files with 266 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/*
* #%L
* Wisdom-Framework
* %%
* Copyright (C) 2013 - 2014 Wisdom Framework
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package controllers.websockets;

public class Data {

public String name;

public int age;

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
/*
* #%L
* Wisdom-Framework
* %%
* Copyright (C) 2013 - 2014 Wisdom Framework
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package controllers.websockets;

import org.apache.felix.ipojo.annotations.Requires;
import org.wisdom.api.DefaultController;
import org.wisdom.api.annotations.*;
import org.wisdom.api.annotations.scheduler.Every;
import org.wisdom.api.content.Json;
import org.wisdom.api.http.websockets.Publisher;
import org.wisdom.api.scheduler.Scheduled;

import java.util.Random;

@Controller
public class WebSocketController extends DefaultController implements Scheduled {

// tag::reception[]
@OnMessage("/socket")
public void onMessage(@Body String message) {
logger().info("Message received : {}", message);
}
// end::reception[]

// tag::receptionWithJson[]
@OnMessage("/jsonSocket")
public void onJsonMessage(@Body Data data) {
logger().info("Data received : name: {}, age: {}", data.name, data.age);
}
// end::receptionWithJson[]

// tag::parameter[]
@OnMessage("/socket/{name}")
public void messageOnSeveralSockets(@Parameter("name") String name, @Body String message) {
logger().info("Message received on {} : {}", name, message);
}
// end::parameter[]

// tag::client[]
@OnMessage("/socket/client")
public void identifyClient(@Parameter("client") String client, @Body String message) {
logger().info("Message received from {} : {}", client, message);
}
// end::client[]


// tag::send[]
@Requires
Publisher publisher;

@OnMessage("/echo")
public void echo(@Parameter("client") String client, @Body String message) {
logger().info("Message received : {}", message);
publisher.send("/echo", client, message.toUpperCase());
}
// end::send[]

// tag::publish[]
@OnMessage("/echo-all")
public void echoAll(@Body String message) {
logger().info("Message received : {}", message);
publisher.publish("/echo-all", message.toUpperCase());
}
// end::publish[]

Random random = new Random();

// tag::binary[]
@Every("5s")
public void binary() {
byte[] bytes = new byte[5];
random.nextBytes(bytes);
logger().info("Message dispatching binary : {}", bytes);
publisher.publish("/binary", bytes);
}
// end::binary[]


// tag::json[]
@Requires
Json json;

@Every("5s")
public void sendJson() {
publisher.publish("/ws/json", json.newObject().put("name", "hello").put("date", System.currentTimeMillis()));
}
// end::json[]

// tag::notification[]
@Opened("/ws/json")
public void opened(@Parameter("client") String client) {
logger().info("Client connection on web socket {}", client);
}

@Closed("/ws/json")
public void closed(@Parameter("client") String client) {
logger().info("Client disconnection on web socket {}", client);
}
// end::notification[]


}
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ include::session-and-scope.ad[]
include::json.ad[]
include::file-upload.ad[]
include::async-http.ad[]
include::websockets.ad[]
include::composition.ad[]
include::asset.ad[]
include::webjar.ad[]
Expand Down
118 changes: 118 additions & 0 deletions documentation/documentation/src/main/resources/assets/websockets.ad
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
== Web Sockets

=== What are web sockets

WebSocket is a protocol providing full-duplex communications channels over a single TCP connection. The WebSocket
protocol was standardized by the IETF as RFC 6455 in 2011, and the WebSocket API in Web IDL is being standardized by
the W3C.

When a client (Browser) wants to establish a connection with a server using a web socket, it starts by a handshake.
Once done, a tunnel connects the client and the server. So, the server can push data to the client and vice-versa. Such
mechanism paves to road to more reactive web applications, where notifications and up to date data are pushed to the
client without having to rely on ajax or long polling.

WebSocket are identified using urls. These urls starts either by +ws://+ or +wss://++.

=== Receiving data

A controller willing to listen for data sent by clients on a specific web socket has to use the +@onMessage+ annotation:

[source, java, indent=0]
----
include::{sourcedir}/controllers/websockets/WebSocketController.java[tags=reception]
----

Every time a client send data on +ws:///localhost:9000/socket+, the callback is called. Notice the +@Body+ annotation
parsing the message to the parameter's type (here as String). The +@Body+ annotation works the same way as in action
methods:

[source, java, indent=0]
----
include::{sourcedir}/controllers/websockets/WebSocketController.java[tags=receptionWithJson]
----

The web socket URI provided in the +@OnMessage+ annotation's parameter can contain dynamic part as for action methods:

[source, java, indent=0]
----
include::{sourcedir}/controllers/websockets/WebSocketController.java[tags=parameter]
----

The +@Parameter+ annotation let you retrieve the dynamic part.s

Finally, you can identify the client sending the data using a special parameter named +client+:

[source, java, indent=0]
----
include::{sourcedir}/controllers/websockets/WebSocketController.java[tags=client]
----

IMPORTANT: Be aware that the client identifier changes if the user disconnects and reconnects.

=== Send data to a specific client

Now that we can receive data from the client, it would be nice to push data to it.

[source, java, indent=0]
----
include::{sourcedir}/controllers/websockets/WebSocketController.java[tags=send]
----

Two important things here:

* The +publisher+ is a service (provided by Wisdom) responsible for sending data to web socket clients.
* We use the +send+ method pushing data to a specific client

So, the previous snippet would produce such a kind of conversation:

----
client >>> hello >>> server
client <<< HELLO <<< server
----

=== Send data to all clients

The previous example send data specifically to one client. However, data can be broadcast to all clients connected
to a specific web sockets:

[source, java, indent=0]
----
include::{sourcedir}/controllers/websockets/WebSocketController.java[tags=publish]
----

The main difference is the usage of the +publish+ method instead of +send+.

==== Sending Json or binary data

So far, we sent only String messages. However, you can send or publish binary data too:

[source, java, indent=0]
----
include::{sourcedir}/controllers/websockets/WebSocketController.java[tags=binary]
----

By the way, notice that this method is not an +OnMessage+ callback, but a method executed every 5 seconds.

You can also send JSON messages directly too:

[source, java, indent=0]
----
include::{sourcedir}/controllers/websockets/WebSocketController.java[tags=json]
----

=== Being notified of client connections and disconnections

In addition to +OnMessage+, there are two other annotations useful to know when clients connect and disconnect from
the listened socket:

[source, java, indent=0]
----
include::{sourcedir}/controllers/websockets/WebSocketController.java[tags=notification]
----

+@Opened+ and +@Closed+ callbacks can also use URI with dynamic parts too. To retrieve the identifier of the client,
just use +@Parameter("client")+.




0 comments on commit 354ba1a

Please sign in to comment.