Java Reference
In-Depth Information
public class WebSocketClient {
public static void main(String[] args) {
try {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
String uri = "ws://localhost:8080/IntroToEE7/acmechat/";
System.out.println("Connecting to " + uri);
container.connectToServer(AcmeChatEndpoint.class, URI.create(uri));
// send and receive messages
} catch (DeploymentException | IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Sending Messages
The ability to asynchronously send messages (text or binary) from a browser client to a server defines the foundation
of AJAX and WebSocket (in HTML5) capability. The WebSockets API allows browser clients to send messages
asynchronously to the server via JavaScript calls to a WebSocket endpoint. Conversely, the API allows clients to
asynchronously receive messages and process them accordingly via a series of JavaScript functions. The following
example demonstrates how to send a message to a WebSocket endpoint by clicking on a button in a web page.
When the button is clicked, a JavaScript function named acmeChatRelay is invoked, which embodies the processing
implementation.
To send a message to a WebSocket endpoint via a JavaScript function, the first task is to confirm whether the
user's browser is capable of working with WebSockets (HTML5 compliant). This confirmation can be done by using
a conditional statement to verify if the “WebSocket” object is available within the client by using the following
if-statement, written in JavaScript.
if("WebSocket" in window){
...
} else {
...
}
If the client browser is capable of working with WebSockets, then the implementation inside of the if block is
invoked, otherwise, the implementation within the else block is invoked. To process the WebSocket message, a new
WebSocket object must be instantiated to establish the server connection, which is done by passing the URL to the
WebSocket endpoint to a new WebSocket object.
var ws = new WebSocket("ws://localhost:8080/IntroToEE7/acmechat");
The constructor for creating a browser client JavaScript WebSocket takes either one or two parameters. The first
parameter is the URL of the server to which the WebSocket will connect, and the second optional parameter is
a String of protocols that can be used for message transmission. The WebSocket object contains a handful of events
that are utilized to help implement message processing. Table 9-1 lists the different events that can occur in the
lifecycle of a WebSocket object, along with a description of what they do.
 
Search WWH ::




Custom Search