Sending and receiving messages
In the following example, we will look at how to send and receive messages using WebSockets technology. We will use a Java WebSocket endpoint as the backend for this example, and HTML and JavaScript as the frontend, to see how can we communicate within our typical web page.
Creating an endpoint
Let's start with the backend part of the example.
A WebSockets application consists of a set of endpoints, each endpoint providing a communication channel that clients can connect to. In the Java WebSockets API, endpoints can be created easily using annotations. Just annotate your class with @ServerEndpoint
to be able to serve WebSockets connections, as shown in the following example:
@ServerEndpoint("/echo") public class EchoEndpoint { .... }
The EchoEndpoint
class now is a WebSocket endpoint resource that is able to accept client connections and perform two-way communication with them. The string parameter "/echo"
represents the URL that this endpoint is mapped to.
Now...